Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is undefined == undefined but NaN != NaN? [duplicate]

Tags:

javascript

I am wondering why undefined == undefined but NaN != NaN.

like image 284
Lenar Hoyt Avatar asked Aug 24 '11 15:08

Lenar Hoyt


People also ask

Why is undefined NaN undefined?

Javascript null represents the intentional absence of any object value. The undefined property indicates that the variable has not been assigned a value or not declared at all. The NaN property represents a “Not-a-Number” value. The NaN property indicates that a value is not a legitimate number.

Why is NaN == NaN false?

When NaN is one of the operands of any relational comparison ( > , < , >= , <= ), the result is always false . NaN compares unequal (via == , != , === , and !== ) to any other value — including to another NaN value.

Is undefined the same as NaN?

undefined isn't converted into any number, so using it in maths calculations returns NaN. NaN (Not-A-Number ) represents something which is not a number, even though it's actually a number.

What does NaN undefined mean?

NaN (Not a Number) is a numeric data type that means an undefined value or value that cannot be represented, especially results of floating-point calculations.


1 Answers

Because that's how it is defined in both the Abstract Equality Comparison Algorithm, and the Strict Equality Comparison Algorithm.

If either operand to == or === is NaN, it returns false.

Abstract

  • If Type(x) is Number, then
    • If x is NaN, return false.
    • If y is NaN, return false.
    • If x is the same Number value as y, return true.
    • If x is +0 and y is −0, return true.
    • If x is −0 and y is +0, return true.
    • Return false.

EDIT: The motivation for the unequal comparison as noted by @CMS is compliance with the IEEE 754 standard.

From the Wikipedia link provided in the comment below:

...The normal comparison operations however treat NaNs as unordered and compare −0 and +0 as equal. The totalOrder predicate will order these cases, and it also distinguishes between different representations of NaNs and between the same decimal floating point number encoded in different ways.

like image 123
user113716 Avatar answered Oct 03 '22 16:10

user113716