Monday, December 16, 2013

What is this undefined thing??

There is a lot of confusion around undefined in Javascript. It seems that many of the developers do checks for undefined without fully understanding what exactly is going on. I think that confusion comes from the fact that undefined is one of the primitive datatypes Javascript comes with, but it's also a property on host object (window in browser environment). So if you imagine:

window.location

which you probably are familiar with, the location is property on window object. This will return location object when accessed. undefined is also a property on window object and its perfectly legal to call:

window.undefined

or in modern browsers:

window.hasOwnProperty(undefined)

When accessed this window.undefined property will return undefined primitive.

It will not return an Object, it will not return a string or a number or boolean which are Javascript datatypes that you are probably familiar with. This property will return primitive undefined that along with string, boolean etc. is simply one of the datatypes that Javascript comes with.

So few examples. What happens when I do check as below?

if(someVar===undefined) {}

someVar is compared against window.undefined property. As this is simply a property on window object it might contain anything really, not necessarily undefined. Imagine someone evil putting this somewhere in a code:

window.undefined=123;

Bad things will happen, people will get fired and projects will be late and anyone without understanding of undefined will be screwed. Now, I might get jumped in here by some developers who actually prefer above syntax over typeof someVar==="undefined". As this is uncommon to reassign undefined property, IMO its fine to use either as long as you understand what is happening (this includes understanding why === is used rather than ==). 

Good news is that in modern browsers with ECMAScript 5 this property is read only, however it's still possible to screw thiongs up for everyone involved with:

(function() { 
    var undefined=66;
    alert(undefined); // will output 66
})()

Ok, another example. Truly silly code ever popular nevertheless:

if(someVar==='undefined') {}

So what is happening here? Some poor dummy compares someVar to "undefined" string basically. He might as well do someVar==='Homer likes beer' and get similar result.

So how to check if something is undefined? Most people seem to prefer:

if(typeof someVar==='undefined') {}

Or if you must:

if(someVar===undefined) {}

Given that you understand what is happening.

To sum it up:

1. undefined is a property on host object (window in browser environment)
2. undefined is primitive datatype Javascript comes with. null, string, boolean etc. are other datatypes you probably are familiar with.
3. although unlikely, undefined property can be assigned different value but only truly evil programmers do that. Be aware however, they are among us.



No comments:

Post a Comment