AppDividend
Latest Code Tutorials

Javascript Number isNaN() Function Example

0

Javascript Number isNaN() Function Example is today’s topic. The isNaN check-in JavaScript always had its issue: it returns true for a value that isnā€™t a number šŸ˜±. Why? Because it coerces the value to a number first, which can falsely result in a NaN. ES6 to the rescue! Number.isNaN won’t forcefully do the conversion. Which means only values of the type number will return true ā€” the Number.NaN() method determines whether the passed value is NaN and its type is Number. The Number.isNaN() method decides whether the value is NaN (Not-A-Number).

Javascript Number isNaN()

The isNaN() method returns true if the value is of the type Number, and equates to NaN. Otherwise, it returns false. Number.isNaN() is different from the globalĀ isNaN()Ā function. The global isNaN() function converts the tested value to a Number, then tests it.

Number.isNaN() does not convert the values to a Number, and will not return true for any value that is not of the type Number.

See the following syntax.

Number.isNaN(value)

TheĀ valueĀ parameter is required, and it is the value that needs to be tested.

#Pass infinite value as a parameter

See the following code.

console.log(Number.isNaN(10/0))

See the output.

āžœ  es git:(master) āœ— node app
false
āžœ  es git:(master) āœ—

#Pass number as a parameter

See the following code.

console.log(Number.isNaN(11))

See the output.

āžœ  es git:(master) āœ— node app
false
āžœ  es git:(master) āœ—

#Pass NaN as a parameter

See the following code.

console.log(Number.isNaN(NaN))

See the output.

āžœ  es git:(master) āœ— node app
true
āžœ  es git:(master) āœ—

#Pass Number in a String as a parameter

See the code.

console.log(Number.isNaN('11'))

See the output.

āžœ  es git:(master) āœ— node app
false
āžœ  es git:(master) āœ—

The global method isNaN() method will return true for the string. See the following code.

console.log(isNaN('Eleven'))

See the output.

āžœ  es git:(master) āœ— node app
true
āžœ  es git:(master) āœ—

So, Number.isNaN() method is a more powerful version of the original, global isNaN().

#Polyfill

The following works because NaN is the only value in javascript which is not equal to itself.

Number.isNaN = Number.isNaN || function(value) {     
    return value !== value;
}

Finally, Javascript Number isNaN() Function Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.