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
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.
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.
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.
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.
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.
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 >
, <
, <=
, >=
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With