Question 9

Question

Can you explain how NaN === NaN evaluates to false?

Answer

It seems counterintuitive that NaN === NaN would evaluate to false. Here's the explanation:

  • NaN's Special Nature: NaN (Not a Number) isn't just any regular value. It represents an undefined or unrepresentable numerical result in JavaScript. Because of this unique status, it doesn't behave like other numbers when compared using the strict equality operator (===).

  • The === Operator: The strict equality operator (===) checks for both value and type equality. For most data types (numbers, strings, booleans), this means:

    • If two values have the same value and are of the same type, they are considered strictly equal.

  • NaN's Exception: When you compare NaN to itself (NaN === NaN), JavaScript doesn't find a true match based on its value or type because NaN isn't a recognizable numerical value in the first place. Therefore, === returns false.

Practical Implications:

  • Careful Comparison: Never rely on === to check if something is NaN. Use the dedicated isNaN() function instead:

    if (isNaN(value)) { 
      // Handle NaN values appropriately
    }

Last updated