pablopunk
pablopunk

Reputation: 371

Why is undefined == undefined true but not undefined <= undefined?

In JavaScript this is true:

undefined == undefined

But this is false:

undefined <= undefined

At first I thought the <= operator included the first one, but I'm guessing it tries to cast it to a number and it fails, but I didn't find any documentation to back this up.

Upvotes: 3

Views: 114

Answers (2)

Andrew Li
Andrew Li

Reputation: 57982

The <= operator coerces both operands into actual Numbers before performing the comparison if both operands are primitives -- while == does not.1 Abstract relational comparison is performed which is where this conversion actually happens. The operation ToNumber is performed on undefined which yields NaN (see the linked table). If you then look at steps 4c and 4d from Abstract relational comparison, if either operand of <= is coerced into NaN, then undefined is returned from Abstract relational comparison. Going back to the first link, you'll see in step 7:

If r is true or undefined, return false. Otherwise, return true.

Since Abstract relation comparison returned undefined, <= evaluates to false.

Less formally, you can see your comparison like this:

const first = Number(undefined); //or +undefined
const two = Number(undefined); //this is NaN
NaN <= NaN

Since NaN == NaN is never true, nor is NaN < NaN, NaN <= NaN is false.


1 undefined == undefined returns true based on the abstract SameValueNonNumber operation which is used with equality operators if both operads are the same value, but not numbers.

Upvotes: 6

Cosmic Voids
Cosmic Voids

Reputation: 67

Read about coercion in JavaScript. About your question, when you apply the equality operator your undefined is coerced to a Boolean. So you got a true result. When you apply the "<=" operator your undefined is coerced to a Number and you get a NaN value and this is the cause of your false result.

Upvotes: -1

Related Questions