Undefined == undefined - true. But undefined> = undefined is false?

I have only a trivial question.

Why is undefined == undefined returns true , but undefined >= undefined is false ?

undefined equals undefined .

But is he not equal or greater?

+44
javascript undefined
Oct 06 '17 at 2:47 on
source share
3 answers

The >= operator >= actually a negation of < . And both refer to the Abstract Relational Comparison Algorithm , which returns undefined for undefined >= undefined , as defined in step 3 (ac). In fact, you can also see that operators with higher (-or-equal) and lesser (-or-equal) are only for working with numbers or strings .

Then, in step 6. of the specification of the >= operator >= you can see why it returns false:

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

+46
Oct 6 '17 at 15:06
source share

undefined === undefined || undefined > undefined undefined === undefined || undefined > undefined and undefined >= undefined , OR in "greater than or equal to" does not match this OR || .

How important this is, comparison operators such as >, <, >= , etc., are for numbers, and undefined is not numbers, undefined is undefined.

What do you expect as a return value with 10 >= "Hello World" ? Of course, false, but again 10 >= "10" returns true , because 10 == "10" is true, and 10 === "10" is false. "10" can be converted to a number so that we see the result that would be returned in the case of a real number, and not a string with numbers.

There is no strict version of the equality operator for >= , unlike != , Which !==

Some really strange and confusing things happen when you try to compare null , undefined , NaN - This is what the JavaScript specification can give an answer, and since JavaScript is a very weakly typed language, and the types are very flexible, so you can compare 10 and "10" and get results that you could only get when you compared two integers in most other languages.

Questions and discussion are more welcome than direct voting. Thank.

+8
Oct 06 '17 at 15:07 on
source share

Inequality operators ( < , > , etc.) cannot be used to compare values ​​that cannot be implicitly converted to numbers. This includes undefined . The reason that you see is because, unlike other languages ​​that cause an error, if you try to do something like this anyway (i.e. TypeError in python), JS allows you to do this. However, the result will always be false.

+2
Oct 06 '17 at 14:57
source share



All Articles