Let\'s say, \"x\" is a variable that never defined, so it should be undefined. In the following scenario:
1)
if(x){//do something}
//ReferenceError: x is
x
will only be the same as window.x
if it was declared (in the global scope, naturally). That can be done with an explicit var
statement in the global scope, or a simple assignment without var
in any scope (which is considered an implicit global declaration):
var a; // declares global a
function foo() {
b = 10; // declares (implict) global b
}
Both a
and b
will also be available as window.a
and window.b
in web browsers.
This also creates a global variable on browsers:
window.c = 20; // can be accessed as just c
Now, trying to access a non-existing variable throws a ReferenceError, while trying to access a non-existing object property just returns undefined.
Interesting fact: globals created with var can't be removed with the delete operator, while implicit globals and those created as properties of the global object can.