I wrote the following code and got no output. Here is the code
var a1 = undefined;
var a2 = 5;
if(a1 > a2)
alert(1);
if(a1 < a2)
alert(2);
if(a1 >= a2)
alert(3);
if(a1 <= a2)
alert(4);
There was no alert box that came up which means that the if statements resulted in false. Can I know the reason?
JavaScript tries to casts the value of x
to number
using ToPrimitive (@RobG). Since x
is undefined, this will return NaN
which compares false to any value. So it will always return false
.
Where expressions using relational operators are involved, the Abstract Relational Comparison Algorithm is used to evaluate the operands, then the result is converted to true
or false
.
In the comparison algorithm, step 3a converts undefined
to NaN
. In step 3c it says that comparing NaN
to anything returns undefined.
In the steps for say the Less-than Operator, a result of undefined
is converted to false.
So for the if statements in the OP, every test returns false
since they are all relational operators that all use the abstract relational comparison algorithm and one of the operands is undefined
.
As @jAndy mentioned in the comments, You can't consider . undefined
keyword as a value/Instanceundefined
is not a numeric type. Rather, it's a special value of the property undefined
of the Global Object
That's why the Expression if(undefined {operator} {operand value})
evaluates to false. But consider the code if(undefined == undefined)
returns true
Hope this Clears the ambiguity!