ES6 – Working with numbers

Hi, in this post we are going to know about the new ways of create numbers and new properties to the Number object.

Binary notation

If we want to represent a numeric constants as binary we can use the “0b” keyword to do that, look this example:

const binaryFive = 0b101;

const five = 5;

console.log(binaryFive === five);

Result:

Octal notation

If we want to represent a numeric constants as octal we can use the “0o” keyword to do that, look this example:

const decimalTwentyNumber = 20;

const octalTwentyNumber = 0o24; // 24 octal is 20 in decimal number

console.log(decimalTwentyNumber === octalTwentyNumber);

Result:

If number is Integer

In ES6 we have a way to check if a number is integer or not, we need to use this code “Number.isInteger( )” because .isInteger is part of the Number object look this example:

let numberA = 19.999;

let numberB = 19.0;

console.log("Is integer? --->", Number.isInteger(numberA));
console.log("Is integer? --->", Number.isInteger(numberB));

Result:

If is a NaN value

The NaN property represents “Not-a-Number” value. This property indicates that a value is not a legal number.

To check whether a value is NaN or not we can use the method isNaN() that is part of the Number object, the syntax is “Number.isNaN(value)

const x = "Cristina";
const y = 12;
const z = NaN;

console.log("x --->", Number.isNaN(x)); // false - because "Cristina" is not a NaN
console.log("y --->", Number.isNaN(y)); // false - because 12 is not a NaN
console.log("z --->", Number.isNaN(z)); // true - because NaN is "NaN"

Result:

Don’t be confuse to use “isNaN( )” method this will check if a value is a number or not.

const x = "Cristina";
const y = 12;
const z = NaN;

console.log("x --->", isNaN(x)); // true - because "Cristina" is "Not a Number"
console.log("y --->", isNaN(y)); // false - because 12 is a number
console.log("z --->", isNaN(z)); // true - because NaN is "Not a Number"

Result:

By Cristina Rojas.