Oct 11, 2016

Some notes about global variable in Javascript

1. In Javascript, if we declare a variable withour using keyword var, the variable always become global.
The mechanics of the scope chain in JavaScript, this ends up being an implicit assignment to a property on the global object (which you can access as window on browsers). See the following example:


function doSomething() {
    var x = 100;
    y = 100;
    return x + y;
}

doSomething();
alert(window.y); // outputs 100


Assuming y isn't declared in any containing scope, it's exactly the same as this:

function doSomething() {
    var x = 100;
    window.y = 100;
    return x + window.y;
}

doSomething();
alert(window.y);



2. As of ES6, a new kind of global was created which isn't a property of the global object: Globals created via let, const, or class. Those new keywords, when used at global scope, create globals that do not become properties of the global object and thus are not accessible via window on browsers.

No comments:

Post a Comment