JavaScript – Checking against NaN

NaN stands for Not-a-Number in JavaScript. Sometimes when writing JavaScript codes, you might need to check whether a variable is a number or not.

For example, you declare a variable foo and assign NaN to the variable, i.e let foo = NaN;. Then you might think checking can be done this way:

let foo = NaN;
foo === NaN; // false
Number.NaN === foo ; // false

However, the expectation is otherwise.

isNaN(foo);  // true
Number.isNaN(foo);  // true

To avoid confusion, please use isNaN() to check whether a variable is Not-a-Number or not.


Author: Wu Chia Chong

My main areas of interest are software architectures and software design methods, patterns, and new trends in software development.