flossfan
flossfan

Reputation: 10854

"varName" in window and varName in window both return true

In JavaScript, why do both of the following return true?

> var a; 
undefined
> "a" in window;
true
> a in window;
true

Is there some kind of type coercion going on, or does JavaScript store a as both a string and as a variable in the window?

Please feel free to rewrite the title of this question - I wasn't sure exactly how to describe this confusing phenomenon.

Upvotes: 0

Views: 68

Answers (2)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

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

Upvotes: 6

jacquard
jacquard

Reputation: 1307

When you say

"a" in window 

javascript looks for a property called a in the window object, and hence returns true.

For

a in window

a evaluates to undefined as noted by @Ootegem and hence returns true.

Upvotes: 2

Related Questions