NaN property in JavaScript

NaN in JavaScript stands for "Not-a-Number". It is a special value that results from an operation that cannot be performed such as division by zero, parsing a non-numeric string where a number was expected, etc.

console.log(0 / 0) // Outputs: NaN
console.log(parseInt('hello')) // Outputs: NaN

In the above examples, NaN is the result of operations that do not produce a well-defined number.

Checking for NaN

You can check if a value is NaN using the isNaN() function:

console.log(isNaN(0 / 0)) // Outputs: true
console.log(isNaN(123)) // Outputs: false

However, isNaN() can be tricky because it first tries to convert the value to a number, which can give unexpected results. For example, isNaN("123") will return false because "123" can be coerced to the number 123.

To overcome this, you can use Number.isNaN() which doesn't coerce the value:

console.log(Number.isNaN('123')) // Outputs: false
console.log(Number.isNaN(NaN)) // Outputs: true

Unique Property of NaN

It's important to note that NaN is the only JavaScript value that is not equal to itself. That means (NaN === NaN) will return false. This is why we need functions like isNaN() or Number.isNaN() to check for NaN.

Understanding NaN can help you avoid common pitfalls and understand the idiosyncrasies of JavaScript a bit better.