I read about undefined in JavaScript, and now I'm not sure if I understand correctly. There is a lot of talk about how to check for undefined , but for some reason I could not find a mention of something that seems fundamental to me to understand how undefined works ( undefined is a property of the host object). It is for this reason that I must confirm that what I understand is correct, and if I am mistaken, I would appreciate clarifications.
Well, first of all, undefined is a property of the host object ( window in browsers), so it is quite legal to use it:
window.undefined
The value of this property is the type "undefined" . This is one of the types of JavaScript along with Object , String , Number and Null . Therefore, if I do this:
if(someVar===undefined) {}
Am I actually checking the window.undefined property that it contains, right?
So, this code below would be pretty stupid, as it will check someVar only on the string "undefined" and not on the type or property of the window object, right?
if(someVar==='undefined') {}
This will also be incorrect, as it will check the window.undefined property (no matter what it contains):
if(typeof someVar===undefined) {}
So, to summarize, the only correct and cross-browser way to check for undefined is to use typeof for example.
if(typeof someVar==='undefined')
Is it correct?
Also in ES5 window.undefined cannot be reassigned, but is it completely legal in older browsers?
This, however, can still be done evil if my understanding is correct:
(function() { var undefined=66; alert(undefined); })()
I would appreciate clarification if I misunderstood how undefined works in JavaScript.