When working with JavaScript, it's important to understand that undefined
can be reassigned. Because of this, it is recommended to create a self-executing function to ensure that undefined
remains undefined. Are there any other values that are loosely equivalent to null/undefined
, apart from the fact that null
and undefined
are definitely ==
?
TLDR
In essence, can you safely replace this:
(function(undefined){
window.f = function(obj){
if(obj===undefined || obj===null ){
alert('value is undefined or null');
}
}
})();
with:
window.f = function(obj){
if(obj==null){
alert('value is undefined or null');
}
}
If the above code is completely safe, why doesn't the JavaScript community/libraries eliminate the use of undefined
altogether and simply use the shorter x == null
conditional to check for both null
/undefined
simultaneously?
EDIT:
I have never encountered someone representing an "unknown value" with 'undefined' instead of null
. It seems like these two values are often misunderstood and not used in their original context. Standardizing the comparison to obj==null
would benefit efficiency and prevent any reassignment issues. Everything would still work as expected.
var obj={};
obj.nonExistantProperty==null // true
var x;
x==null // true
function(obj){
obj==null // true
}
The only exception to this rule appears to be when converting undefined
/null
to an integer. While this scenario is rare, it should still be mentioned.
+(null)==0
while
isNaN(+undefined)
Since NaN is the only value in JavaScript that is not equal to itself, some interesting comparisons can be made:
+undefined == +undefined // false
+null == +null // true
Using null
as a loose equality using ==
instead of undefined
is safe, unless you plan on converting the value to an integer which is an uncommon scenario.