Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't undefined less than 1?

Tags:

So in most cases I've been able to use something similar to these lines, but Javascript has given me this weird result.

If I take some value and it turns out to be undefined, when compared to an integer, it does not appear to be less than or greater than any number. Why is this?

if(undefined < 1 || undefined >= 1)
    alert("yes");
else
    alert("no");

//this always alerts no

JSFiddle

like image 907
Liftoff Avatar asked Mar 02 '14 22:03

Liftoff


People also ask

What is the value of undefined +1?

undefined is not being converted to anything. You perform a + operation with operands 1 (Number) and undefined . The result of Number + undefined is not a number or NaN . NaN is a special kind of Number , like Infinity and it has some very peculiar properties.

How do you know if undefined is undefined?

In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. If the value is not defined, typeof returns the 'undefined' string.

Is undefined equal to itself?

JavaScript probably tries to convert them to some comparable values, e.g. a number. But undefined converted to a number is NaN, which is neither equal to itself nor greater than itself. It's Javascript. Don't attempt to use logic.

Why undefined === undefined is false?

So undefined really means undefined. Not False, not True, not 0, not empty string. So when you compare undefined to anything, the result is always false, it is not equal to that.


2 Answers

There is no operator '<' can not be applied to type 'undefined' error in JavaScript as you would find in other typed languages. As such, JavaScript evaluates incompatible types with an operator to false.

like image 134
Reactgular Avatar answered Oct 04 '22 20:10

Reactgular


That's just how javascript works. If either side can't be converted to a number (strings can, by code point comparison: '2' < '3' && '186' < '4'), than number comparisons will return false (works with >, <, <=, >=).

like image 24
bjb568 Avatar answered Oct 04 '22 22:10

bjb568