Related Tags

es6
javascript

# Global number methods in ES6

JavaScript has multiple global number methods that make it easy to work with numbers. In this shot, we will cover the new and improved number methods introduced with ES6.

Number method Description
Number.isInteger() Determines if the passed value is an integer.
Number.isNaN() Determines if the passed value is NaN.
Number.isFinite() Determines if the passed value is a finite number.
Number.isSafeInteger() Determines if the passed value is a safe integer (between $(-2^{53}, 2^{53})$
Number.parseInt() Parses a string argument and returns an integer of the specified radix.
Number.parseFloat() Parses a string argument and returns a float representation of the passed string.

A lot of these functions are not new. For example, JavaScript has had a method called isNaN() that is exposed through the window object. However, these functions have issues that ES6 number methods aim to solve.

## Code

Examples of using Number.isInteger():

// prints 'true'
console.log(Number.isInteger(10));

// prints 'false'
console.log(Number.isInteger(10.5));

Examples of using Number.isNaN():

// prints 'true'
console.log(Number.isNaN(0/0));

// prints 'false'
console.log(Number.isNaN(undefined));

Examples of using Number.isFinite():

// prints 'true'
console.log(Number.isFinite(10));

// prints 'false'
console.log(Number.isFinite(null));

Examples of using Number.isSafeInteger():

// prints 'true'
console.log(Number.isSafeInteger(10));

// prints 'false'
console.log(Number.isSafeInteger(Math.pow(2, 53)));

Examples of using Number.parseInt():

// Prints '-5'
console.log(Number.parseInt('-5'));

// Prints '4'
console.log(Number.parseInt('100', 2));

Examples of using Number.parseFloat():

// Prints '10'
console.log(Number.parseFloat('10'));

// Prints 'NaN'
console.log(Number.parseFloat('test'));

RELATED TAGS

es6
javascript