Why NaN == NaN is False in JavaScript – Asked in an HCL Tech Interview


Our Javascript Code Expression:

console.log(NaN == NaN);

Step-by-Step Breakdown

🔸 Step 1: What is NaN?

NaN stands for "Not a Number", and it represents a value that is not a valid number.

Examples that result in NaN:

  • "abc" / 2 // NaN
  • Math.sqrt(-1) // NaN
  • parseInt("hello") // NaN

It’s still a type of number, but it means "an invalid number".

typeof NaN // "number"

🔸 Step 2: What Does == Do?

  • The == operator checks equality, allowing type coercion if needed.
  • But even with coercion, NaN is never equal to anything, not even itself.


🔸 Step 3: Why is NaN == NaN false?

This is defined in the IEEE 754 floating-point standard, which JavaScript follows.

According to this spec:
“NaN is not equal to any value, including itself.”

So even if you write:

let a = NaN;
let b = NaN; console.log(a == b); // false

It’s still false.


✔ Final Answer:

B) false

This question appeared in the HCL Tech 2nd round of interview, testing the candidate’s knowledge of NaN and loose equality (==) operator in JavaScript.


How to Properly Check for NaN?

Since you can't use == or === to check for NaN, JavaScript gives you a built-in method:

🔹 Use Number.isNaN()

Number.isNaN(NaN);     // true
Number.isNaN("abc");   // false

Bonus Point: Object.is(NaN, NaN)

If you're looking for strict identity comparison, use:

Object.is(NaN, NaN); // true

Unlike == or ===, Object.is() considers NaN equal to NaN.


Summary

ExpressionResultWhy?
NaN == NaNfalse           NaN is not equal to itself
NaN === NaN         falseEven strict equality fails
Number.isNaN(NaN)trueProper way to check for NaN
Object.is(NaN, NaN)trueAnother correct comparison tool

Post a Comment

Previous Post Next Post