Many variable scope nuances can be found throughout JavaScript. The following is by no means a comprehensive list, but it covers the most common cases:
for (var n = 4; false; ) { } console.log(n);
This is due to the fact that, in JavaScript, variable definition happens at the beginning of the corresponding scope, not just when it is declared.
if
statement define a variable inside the function with the same name, even if that if
branch isn't reached, it is redefined. An example:var x = 1; function foo() { if (false) { var x = 2; } return x; } foo(); // Return value: 'undefined', expected return value: 2
Again, this is caused by moving the variable definition at the beginning of the scope with the undefined
value.
window
object.window.a = 19; console.log(a); // Output: 19
a
in the global scope means a
as an attribute of the current context, so a===this.a
and window
object in a browser act as an equivalent of the this
keyword in the global scope.
The first two examples are a result of a feature of JavaScript known as hoisting, which will be a critical concept in the next section about writing functions.