isNaN()
If the argument passed inside isNaN() is NaN, then true is returned at the first place, but if the it is not, then it is coerced into number and if the result is NaN, then true is returned else false is returned.
For example,
- Empty string ('') is coerced into 0
- null is coerced into 0
- undefined is coerced into NaN
- false is coerced into 0
console.log(+'') // 0
console.log(Number('')) // 0
console.log(Number(false)) // 0
console.log(Number(null)) // 0
console.log(Number(undefined)) // NaN
console.log(Number(NaN)) // NaN
console.log(Number({}) // NaN
console.log(Number(Infinity)) // Infinity
Now let's see isNaN() in action
console.log(isNaN(+'')) // false, because 0 is not NaN
console.log(isNaN(false)) // false, because is 0 is not NaN
console.log(isNaN(undefined)) // true, because Number(undefined) is NaN
console.log(isNaN(NaN)) // true, because NaN is NaN
console.log(isNaN({}) // true, because Number({}) is NaN
console.log(isNaN(null)) // false, because Number(null) is 0 and 0 is not NaN
console.log(isNaN(Infinity)) // false, because Infinity is a Number and Number is not NaN
Number.isNaN()
It works somewhat different from global isNaN(). Here the argument is not coerced into a number, rather it checks whether the argument is NaN or not. If it is NaN then true is returned, else false is returned.
console.log(Number.isNaN('abc')) // false
console.log(isNaN('abc')) // true
In the first example Number.isNaN('abc'), here 'abc' is clearly a string and it is not NaN, therefore it returns false.
In the second example isNaN('abc'), here 'abc' is coerced into a number type and Number('abc') is NaN, therefore it returns true.
Some more examples:
console.log(Number.isNaN({})) // false
console.log(isNaN({})) // true
In the first example, {} is clearly not a NaN, therefore false is returned.
In the second example, {} is coerced into a number and Number({}) is NaN, therefore true is returned.
console.log(Number.isNaN(false)) // false
console.log(isNaN(false)) // false
In the first example, false is clearly not NaN, therefore false is returned.
In the second example, as I have discussed earlier in this article that false is coerced into 0 and 0 is certainly a number, therefore false is returned.
I hope you have got the point, at last I am writing some snippets that will help you more, getting the nuances.
console.log(Number.isNaN(NaN)) // true, because NaN is NaN
console.log(Number.isNaN(undefined)) // false, because undefined is not NaN
console.log(Number.isNaN(null)) // false, because null is not NaN
console.log(Number.isNaN('')) // false, because '' is not NaN
console.log(Number.isNaN(false)) // false, because false is not NaN
console.log(Number.isNaN({})) // false, because {} is not NaN
console.log(Number.isNaN(Infinity)) // false, because Infinity is not NaN
Top comments (0)