views:

279

answers:

2

Can someone explain way this work

if(window.a){}

while this is failing

if(a)

In both cases a is undefined.

A: 

undefined is not a true of false affirmation, so you cannot check it using if(undefined).

If you want to check if your variable is defined, you can do this :

if( typeof(yourVariable) != "undefined") {
alert("Variable is defined");
}
rnaud
I know, but the question was why window.a still passes. I mean this is also undefined.
eskimoblood
still, if(window.a) is not the right way to check it. typeof(window.a) == typeof(a) == "undefined"window is always defined, so any property of it will not error out as an undefined/undeclared variable would (if you type it in the console for example)
rnaud
+4  A: 

window.a is a property of window and it's undefined. a is a variable, and it's undeclared.

To use a variable, you should first declare it using the var statement. Since you didn't declare a, the interpreter raises an error. Object properties are not needed to be explicitly declared in order to use them. Crockford writes in The Good Parts:

If you attempt to extract a value from an object, and if the object does not have a member with that name, it returns the undefined value instead.

Török Gábor
However: "window.a = 2; a" -- No 'var' is needed. It just happens that the exception is thrown when an "un-prefixed" identifier look-up runs out of chained scopes to look in. The last context checked is the global context (or 'window'). For most practical purposes, 'var x' in the global context is the same a 'window.x = undefined'. See http://jibbering.com/faq/faq_notes/closures.html and look at "Identifier Resolution, Execution Contexts and Scope Chains".
pst
@pst: that's a special case in browsers that all global variables are property of `window`. It's an independent problem of JavaScript. If you run `window.a = 2; a` in Rhino which is a non-browser environment, you still get the reference error.
Török Gábor
@pst: anyway, thanks for your supplement in clarifying the answer.
Török Gábor
@Török: Just to clarify further, if you ran `this.a = 2; a` (in the global scope, or standalone function call) though, it would work in any environment. There is still a global object, it's just not always called `window`.
Matthew Crumley