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 not defined
2)
if(window.x){//do something}
//worked as expected
As far as I know, in browser environment here, x should be the same as window.x, could anyone help to point out the reason for the different behavior here?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With