Saturday, November 9, 2024

JavaScript, NaN with comparison operator

In JavaScript, the comparison operators behave differently when one of the operands is NaN. Here are the key rules:

Equality (==) and Strict Equality (===):

  • NaN is never equal to any value, including itself.
  • NaN == NaN and NaN === NaN both return false.
Example:
NaN == NaN; // false
NaN === NaN; // false

Other Comparison Operators (<, >, <=, >=):

When comparing NaN with any other value using these operators, the result is always false. This is because NaN is not considered greater than or less than any value, including itself.
Example:
NaN < 5;  // false
NaN > 5;  // false
NaN <= 5; // false
NaN >= 5; // false

Special Note:
To check if a value is NaN, use the Number.isNaN() function or the global isNaN() function, not the comparison operators:
Number.isNaN(NaN); // true
isNaN(NaN); // true
The behavior of NaN in comparisons ensures that NaN is treated as a unique, non-comparable value in JavaScript.

No comments:

Post a Comment

Hot Topics