What is the only value not equal to itself in JavaScript?

JavaScript, Type, Comparison · Dec 12, 2021

NaN (Not-a-Number) is the only JavaScript value not equal to itself when comparing with any of the comparison operators. NaN is often the result of meaningless or invalid math computations, so it doesn't make sense for two NaN values to be considered equal.

const x = Math.sqrt(-1); // NaN
const y = 0 / 0;         // NaN

x === y;                 // false
x === NaN;               // false

Number.isNaN(x);         // true
Number.isNaN(y);         // true

isNaN(x);                // true
isNan('hello');          // true

You can check for NaN values using the Number.isNaN() function. Note that this is different from the original , global isNaN(). Their difference lies in the fact that isNaN() forcefully converts its argument to a number, whereas Number.isNaN() doesn't. This is why Number.isNaN() is considered more robust and preferable in most cases.

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • JavaScript Comparison

    Comparing values in JavaScript is one of the most common tasks, yet it has a lot of things you should bear in mind.

    Collection · 11 snippets

  • Value is plain object

    Checks if the provided value is an object created by the Object constructor.

    JavaScript, Type · Oct 20, 2020

  • Value is string

    Checks if the given argument is a string. Only works for string primitives.

    JavaScript, Type · Oct 20, 2020

  • Value is generator function

    Checks if the given argument is a generator function.

    JavaScript, Type · Oct 20, 2020