According to What is the difference between null and undefined in JavaScript?, null and undefined are two different objects (having different types) in Javascript. But when I try this code
var a=null;
var b;
alert(a==null); // expecting true
alert(a==undefined); // expecting false
alert(b==null); // expecting false
alert(b==undefined); // expecting true
The output of the above code is:
true
true
true
true
Now as == only matches the value, I thought that both undefined and null must have the same value. So I tried:
alert(null) -> gives null
alert(undefined) -> gives undefined
I don’t understand how is this possible.
Here is the demo.
Edit
I understand that === will give the expected result because undefined and null have different types, but how does type conversion work in Javascript in the case of ==? Can we do explicit type conversion like we do in Java? I would like to apply a manual type conversion on undefined and null.
You need to use the identity operator
===, not the equality operator==. With this change, your code works as expected:The reason the equality operator fails in this case is because it attempts to do a type conversion.
undefinedis of typeundefined, andnullis of typeobject; in attempting to compare the two, Javascript converts both tofalse, which is why it ends up considering them equal. On the other hand, the identity operator doesn’t do a type conversion, and requires the types to be equal to conclude equality.Edit Thanks to @user1600680 for pointing out, the above isn’t quite correct; the ECMAScript specification defines the null-to-undefined as special case, and equal. There’s no intermediate conversion to
false.A simpler example of type conversion is number-to-string:
The above answer has a good quote from Douglas Crockford’s Javascript: The Good Parts:
If you don’t believe that the rules are complicated and unmemorable, a quick look at those rules
will disabuse you of that notion.