Understand the difference between isNaN and Number.isNaN
Victory Osikwemhe
Posted on June 18, 2020
Before we take a dive into the difference between isNaN and Number.isNaN, let's take a look at what NaN is
According to the javascript spec NaN stands for Not a Number, when you encounter something like this in javascript, you will have to cross check what you are trying to do it's either
- you are trying to carry out an invalid mathematical operation or
- you are trying to cast something that's not a number (except for a string of numbers) to a number for example
parseInt('hello'); // a string of characters cannot be converted to a number therefore the operation will return NaN
Number(undefined); // NaN
'string'/2; // NaN
One thing you have to know is that you cannot compare NaN to NaN or Number.NaN, therefore
parseInt('hello world') === parseInt('hello world'); // false
So you know, this does not have to do with strict equality comparison or abstract equality comparison
parseInt('foo') == parseInt('foo'); // false
But you can actually make a check for the above with Object.is
Object.is(parseInt('foo'), parseInt('foo')); // true
Object.is(NaN, NaN); // true
Apart from using Object.is , you can also check if a value is NaN, which can be done with
- isNaN // on the global object
- Number.isNaN
Which ever one you choose will determine how you will get backstabbed by javascript.
So this bring us to the difference between isNaN and Number.isNaN
isNaN does two things
- It checks if the value passed to it is NaN or
- It will try to coerce the passed value into a number if the result is NaN then the return value will be true
Number.isNaN does only one thing
- It checks if the current value passed in actually NaN
for example
isNaN('javascript'); // true
The reason for this is because isNaN coerces 'javascript' to a number and since javascript is not a number the return value is false
Number.isNaN('javascript'); // false
The reason for this is because 'javascript' is a string and not the value NaN, so the return value will be false
isNaN(NaN); // true
NaN is not a number hence true
Number.isNaN(NaN); // true
NaN is not a number hence true
What you should get from the above is that Number.isNaN does not do any form of coercion, it just check if the value passed to it is NaN, if it's not NaN then the return value will be false.
Open to corrections, this is my first ever article. Thanks for reading
Posted on June 18, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.