No, you declared a variable called a
, which is initialized to undefined
. This variable is global, so it can be accessed as a sort-of property of the global object (window), so:
var a = {};//an obejct
var b = {};//another
b === a //false, two separate objects, of course but
window.a === a;//true
That's why 'a' in window
is true. It's similar to window.hasOwnProperty('a');
. Similar, not the same thing.
The second check you did (a in window
) is evaluated to undefined in window
, in turn the value undefined
is stringified, so the expression is finally evaluated to 'undefined in window'
, which is always going to be true.
I admit, this is confusing, because undefined
is both a value and a property, which doesn't really make sense. It's just one of the quirks in JS you have to learn to live with. You can verify this like so:
window.hasOwnProperty('undefined');//true
window.undefined;//undefined of course
window.hasOwnProperty('null');//false
typeof null;//object (really! But it is actually a primitive
typeof undefined;//undefined
null
is an object for historic reasons, but I'm not going to give you "The unabridged history of ECMAScript", Just thought you might like to know that.
What you have to keep in mind is how JS resolves variable names, and expressions. I've explained this many times, see this answer and all of the links at the bottom for details on the matter