JavaScript undefined replaced with null

Viewed 10353

In JavaScript undefined can be reassigned, so it is often advised to create a self executing function that assures undefined is actually undefined. As an alternative null and undefined are definitely == but are any other values loosely equivalent to null/undefined?

TLDR

Basically 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 is 100% safe, why doesn't the JavaScript community/libraries drop undefined altogether and use the shorter x == null conditional to check for both null/undefined at once?

EDIT:

I have never seen someone actually represent an "unknown value" with 'undefined' vs null? I have never seen this scenario, and is why I originally asked the question. It just appears to be two incredibly confused values that are never used in their original intent. Standardizing everything to do a comparison obj==null would be beneficial for size and avoid any issues with reassignment. Everything would continue to work

var obj={};
obj.nonExistantProperty==null // true

var x;
ix==null // true

function(obj){
  obj==null // true
}

The one exception to this rule appears to be when casting undefined/null to an integer. This is a pretty age case scenario, but definitely should be noted.

+(null)==0 while isNaN(+undefined)

Considering NaN is the only value in JavaScript not equal to itself, you can do some pretty crazy things like:

+undefined == +undefined // false
+null == +null // true

Using null as a loose equality == drop in replacement for undefined is safe, provided you don't plan to cast the value to an integer. Which is a pretty edge case scenario.

4 Answers
Related