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.
JavaScript (as a core language) does not provide any way to access the object containing all global variables (the "Global Environment") but it exists nonetheless. In Web browsers, the Global Environment has a variable named window
(and also self
, and perhaps top
) that references the global context.
You can type window.window.self.top.window.top.window.x
if you like. :)
Thus, in a context without a local var x
or var y
defined, this code
x = 42;
window.y = 17;
…will assign both variables in the global context, and this code:
console.log(window.x);
console.log(y);
…will read the values from the global context.
JavaScript (like Lua and Ruby) lets you set the value for a global variable without predefining the variable as global. (Note, however, that this is disallowed in ECMAScript5 strict mode.)
However, JavaScript (unlike Lua and Ruby) explicitly does not allow you to access an unset global variable. (See ECMAScript 5 specification section 8.7.1, step 3.) It does this to protect you slightly from accidentally reading a global variable when you made a typo. In Lua you can write:
myLongNamedGlobalVariable = 42 -- assign to a global variable
print(myLongNamedGlobalVeriable) --> nil (wtf!)
and not realize that you've made a typo. In JavaScript, you are protected from this by the ReferenceError.