Scopes in JavaScript
Visibility rules are unique to JavaScript, they should be understood to avoid headaches.
In JavaScript, declarations are static and assignments are dynamic. This has the effect that a declaration may be placed anywhere in the code, it will be taken into account before any assignment. This has very specific effects that we will discuss ...
All the logic of the language is based on two rules:
- Declaration are static and evaluated before executing the code.
- A function is the only local scope. Function contained in another function has access to variables of the function that contains it, and the global variables, but not vice versa.
Only functions give a local scope to variable, control structures do not have this effect. For a variable declared as local, the assignment is done with the var prefix.
A first example to show that a declaration in a function limits the visibility in this function.
var x = 1;
var y = 1;
function test1()
{
x = 10;
var y = 10;
}
test1();
document.write("x = " + x);
document.write("y = " + y);
X and y are both assigned the value 10 in the function. Y is redeclared therein, which makes it is assigned locally while x is assigned in the global scope, even if the assignment is made in the function.
These rules also apply to the for control structure.
function test2()
{
a = 10;
for(i = 0; i < 10; i++)
{
a = a + 2;
}
}
test2();
document.write("a = " + a);
document.write("i = " + i);
We see that both the a and i variables are assigned globally and we also see that i after the execution of the loop is 10, the upper limit of the conditional test. This usually does not make a difference until you use a recursive function, in which case the index i could be incremented indefinitely.
Now we add a declaration of the loop variable, but after using this variable and without assigning it again.
var b = 3;
var j = 3;
function test3()
{
var b = 10;
for(j = 0; j < 10; j++)
{
b = b + 2;
}
var j;
}
test3();
document.write("b = " + b);
document.write("j = " + j);
You can verify in this example that the position of the declaration is irrelevant: it is sufficient that the variable is declared somewhere in the function so that it becomes local and it can be declared after use!