This page looks best with JavaScript enabled

Equality Checks using NaN in Javascript

 ·   ·  ☕ 2 min read

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 -

1
2
3
4
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.

1
2
3
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.

1
2
3
4
5
6
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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
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. NaN is the only object that does not equal itself in Javascript.
  • typeof NaN outputs Number. Yes, you read that right
1
console.log(NaN == NaN); // false

For more such silliness head over to know all things about undefined and null in Javascript.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things