Scripter Javascript Tutorial
javascriptmusiclogicscripterbookexcerpttutorial37 Variable Scope
MDN: Grammar and Types: Variable Scope
An important concept to understand about functions is scope. Whenever a variable a declared within a function, then that variable is local to the function. This means the variable cannot be called from outside the function.
function add( operand1, operand2 ) {
var sum = operand1 + operand2;
return sum;
}Trace(operand1);
In the above example, the Trace()
function tries to use
the operand1
variable, which is declared as one of the
function’s arguments. Because the variable is within the function but is
called from outside the function, Scripter will display the
following error in the console:
[JS Exception] ReferenceError: Can't find variable: operand1 line:5
The variable operand1
simply does not exist outside of
the add
function. However, variables declared
outside of the function can be used from within the
function. The following is a contrived, almost useless example, but the
concept will be important to grasp when discussing Scripter’s own
variables which can be used from anywhere in a script.
function add() {
var result = opr1 + opr2;
return result;
}
var opr1 = 2;
var opr2 = 3;
var sum = add(); // sum = 5
In the above example:
Line 1: The
add
function is declared but without any arguments.Line 2: The result is determined by the two variables which are declared on lines 6–-7;
Line 3: The result is returned.
Line 8: The
add
function is called without any arguments. Note the parentheses are still needed to actually invoke the function.