I just have more of a trivial question.
Why does undefined == undefined
return true
, but undefined >= undefined
is false
?
undefined
is equal to undefined
.
But it is not equal to or greater?
I just have more of a trivial question.
Why does undefined == undefined
return true
, but undefined >= undefined
is false
?
undefined
is equal to undefined
.
But it is not equal to or greater?
The >=
operator is essentially the negation of the <
operator. And both invoke the Abstract Relational Comparison Algorithm which returns undefined for undefined >= undefined
as defined in step 3 (a to c). Actually, you can also see that the greater-than(-or-equal) and less-than(-or-equal) operators are only meant to work with either numbers or strings.
Then in the 6. step of the specification of the >=
operator, you can see why it returns false:
If
r
is true or undefined, return false. Otherwise, return true.
undefined === undefined || undefined > undefined
and undefined >= undefined
, the OR in "greater than or equal to" is not the same as this OR ||
.
As far as it is concerned the comparison operators like >, <, >=
etc are meant for numbers and undefined
isn't numbers, undefined
is undefined.
What would you expect as a return value when 10 >= "Hello World"
? Of course a false, but again 10 >= "10"
returns true
because 10 == "10"
is true and 10 === "10"
is false. The "10" can be converted into a number so we see the result that would have been returned in case of an actual number and not a string with numbers.
There is no strict equality operator version for >=
as opposed to !=
which is !==
Some really weird and confusing things happen when you try comparing null
, undefined
, NaN
- This is something that the specification of JavaScript may be able to answer and since JavaScript is a very loosely typed language and the types are very flexible that is why one can compare 10
and "10"
and still get results which you may have gotten only when you compared two integers in most of the other languages.
Inequality operators (<
, >
, and so on) cannot be used to compare values that cannot be implicitly converted to numbers. This includes undefined
. The reason behind what you're seeing is that, unlike other languages that throw an error if you try to do something like this anyway (i.e. TypeError
in python), JS lets you do it. However, the result will always be false.