exebook
exebook

Reputation: 33900

Equal but not greater-or-equal?

Сomparing anything with undefined has been discussed many times, but today I had to compare items in arrays and, at some point, items in the array could be undefined and I was curious how they will compare to each other. I found that undefined == undefined is true, but at the same time undefined >= undefined is not true. Wait a second, if something is equal, then greater-or-equal also mean to be true? That is how logic works!

I can accept anything that ECMA Standard is saying, I believe those guys are sane and have a good reason for everything. But what on the earth could be a reason for this comparison behavior? If I was implementing undefined I would return undefined for any comparison that has undefined as an operand. But they choose to return boolean, and then why the results are like this?

Now I think the best solution is just to handle any appearance of undefined in a special way with multiple of if statements.

    undefined === undefined: true
    undefined == undefined: true

    undefined !== undefined: false
    undefined != undefined: false
    undefined < undefined: false
    undefined > undefined: false
    undefined <= undefined: false
    undefined >= undefined: false

Upvotes: 10

Views: 163

Answers (1)

zzzzBov
zzzzBov

Reputation: 179046

But what on earth could be the reason for this comparison behavior?

The ECMAScript specification was not written to describe how JavaScript should work, it was written to describe how JavaScript actually works.

The language was implemented rapidly in Netscape Navigator, and contained many "bugs" such as this, which were then copied in IE's implementation. Eventually, ECMAScript was standardized, but not until after JavaScript existed in the wild. Standardizing any language that's already being used requires a certain amount of backwards compatibility.

<= and >= diverge from == simply because the standard says so. The standard says so because that was how they were implemented initially.

Upvotes: 3

Related Questions