I’ve been reading about undefined in JavaScript and now I am not sure if my understanding is correct. There is a lot of talk around how to check for undefined but somehow I couldn’t find any mentioning of something that to me seems fundamental to understanding of how undefined actually works (undefined being property on host object). This is the reason for this question, I need to confirm that what I understand is correct and if I’m wrong I would appreciate clarification.
Okay, first of all, undefined is property on host object (window in browsers) so it’s perfectly legal to use:
window.undefined
The value of this property is type "undefined". This is one of the JavaScript types along with Object, String, Number and Null. So if I do:
if(someVar===undefined) {}
I’m actually checking against window.undefined property, whatever it contains, is that right?
So this code below would be pretty dumb as this would check someVar only against the string "undefined", not the type nor the property of the window object, right?
if(someVar==='undefined') {}
This below would be also incorrect as this would check against the window.undefined property (whatever it contains):
if(typeof someVar===undefined) {}
So, to sum it up, the only proper and cross-browser way to check for undefined is to use typeof e.g.:
if(typeof someVar==='undefined')
Is that right?
Also in ES5 window.undefined cannot be reassigned but it’s perfectly legal in older browsers right?
This however can still be done and is evil if my understanding is right:
(function() {
var undefined=66;
alert(undefined);
})()
I would appreciate clarification if I misunderstood how undefined works in JavaScript.