Variable Scope |
Active Web |
Variable scope refers to the visibility of variables. Scope is only relevant for function calls; all code can see all variables until a function call is executed, then the scoping rules come in to play. There are two basic rules:
Variables created in code are visible inside all functions called by that code.
Variables created inside functions are not visible to the code that called the function.
When a function is called it is given its own variable scope to execute in. All variables created inside the function are part of this function scope and this scope is discarded when the function returns. This means that all variables created inside the function are not visible outside the function. Variables created in the code that called the function are visible inside the function.
When a variable is declared with a ‘var’ statement it is created inside the current scope. If the variable is inside a function, than that scope is the function scope and so the variable is available to the function in which it is defined, and all functions below it. If a variable is used without declaring it in a ‘var’ statement, which is allowed, then on the first use a check is made to see if a variable with that name exists in scope, if it does then that variable is used, otherwise a new variable is created. This means that if a variable of that name exists outside the function then it will be used rather than creating a new variable.
Example 1
function myFunction() {
var j = 10;
}
for (var j = 0; j 10; j++) {
myFunction();
writeln(j);
}
Example 2
function myFunction() {
j = 10;
}
for (var j = 0; j 10; j++) {
myFunction();
writeln(j);
}
In example 1 the code will write out the numbers 0 to 9, but in the second example the code will only write out the number 10 as the variable ‘j’ in ‘myFunction’ has not been declared with a ‘var’ statement, and thus uses the variable ‘j’ defined in the calling code.
Because of the visibility of variables in a higher scope (i.e. the calling code) it is strongly recommended that all variables inside functions should be declared with the 'var' operator before they are used, to avoid the inadvertent use of a variable in a higher scope. |
Topic ID: 150115