It is easy to take NaN for granted. But remember - the ’not a number’ notation is the only powerful object that does not equal itself.
First the essentials - you use NaN whenever you do not have variable values in control but want to do a numerical operation on it. Rather than the numerical operation throwing you under the bus, you play safe by checking whether the numbers can be used in a valid way.
Now, consider this -
console.log(isNaN("abc")); // true
console.log(isNaN("123")); // false
console.log(isNaN(123)); // false
console.log(isNaN("123abc")); // true
All results are on expected lines. If a given variable is not a number (e.g. ‘abc’) the NaN check returns true. Else, it returns false. However note that strings that contain valid numbers are coerced into their numerical forms and evaluated.
The results continue on the same lines for any numerical operations that you force anyway.
console.log(isNaN(0 / 0)); // true
console.log(isNaN(0 / "a")); // true
console.log(isNaN("1" + "a")); // true
But, be careful about using NaN and 0.
console.log(parseInt(10)); // 10
console.log(parseInt("abc")); // NaN
console.log(!!parseInt("abc")); // false
// false, since NaN is false in boolean language!
console.log(!!parseInt(0)); // false
So, you may have to ideally check for both non-zero and for NaN when checking for existence of numbers.
let x = 0;
if (x == 0 || !isNaN(x)) {
console.log(" valid number 0 ");
}
x = "123";
if (x == 0 || !isNaN(x)) {
console.log(" valid number 123 ");
}
x = "a";
if (x == 0 || !isNaN(x)) {
console.log(" valid number a ");
}
/* output
valid number 0
valid number 123
*/
Also, note that -
- you cannot really compare two NaN’s - they are not a match made anywhere.
NaNis the only object that does not equal itself in Javascript. typeof NaNoutputsNumber. Yes, you read that right
console.log(NaN == NaN); // false
For more such silliness head over to know all things about undefined and null in Javascript.