Sobes.tech
Junior

How to check if a value is NaN?

sobes.tech AI

Answer from AI

There are several ways, the most reliable is to use the Number.isNaN() function.

  1. Number.isNaN(): This is the preferred method because it correctly distinguishes between NaN and other non-numeric values that convert to NaN when coerced to a number (e.g., objects).

    // Returns true only for NaN
    console.log(Number.isNaN(NaN));       // true
    console.log(Number.isNaN(undefined)); // false
    console.log(Number.isNaN({}));       // false
    console.log(Number.isNaN('abc'));    // false
    console.log(Number.isNaN(null));      // false
    console.log(Number.isNaN(0 / 0));     // true
    
  2. isNaN() (global function): This function converts the argument to a number before checking. Because of this, it can return true for values that are not NaN but cannot be converted to a number. Avoid using it for strict NaN checks.

    // Returns true for NaN and some non-numeric values
    console.log(isNaN(NaN));       // true
    console.log(isNaN(undefined)); // true
    console.log(isNaN({}));       // true
    console.log(isNaN('abc'));    // true
    console.log(isNaN(null));      // false
    
  3. Comparison with itself: The JavaScript specification states that NaN is the only value that is not equal to itself. This method is reliable and works, but Number.isNaN() is more readable.

    // true only if the value is NaN
    const value = NaN;
    console.log(value !== value); // true
    
    const anotherValue = 5;
    console.log(anotherValue !== anotherValue); // false
    

It is recommended to use Number.isNaN() for precise NaN checking.

How to check if a value is NaN? — Node.js - sobes.tech