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 -
|
|
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.
|
|
But, be careful about using NaN and 0
.
|
|
So, you may have to ideally check for both non-zero and for NaN when checking for existence of numbers.
|
|
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
outputsNumber
. Yes, you read that right
|
|
For more such silliness head over to know all things about undefined and null in Javascript.