Variable Scope

Microsoft Office JScript

Microsoft® JScript® Variable Scope
 JScript Tutorial;
Previous
Next


Microsoft JScript has two scopes: global and local. If you declare a variable outside of any function definition, it is a global variable, and its value is accessible and modifiable throughout your program. If you declare a variable inside of a function definition, that variable is local. It is created and destroyed every time the function is executed; it cannot be accessed by anything outside the function.

A local variable can have the same name as a global variable, but it is entirely distinct and separate. Consequently, changing the value of one variable has no effect on the other. Inside the function in which the local variable is declared, only the local version has meaning.

var aCentaur = "a horse with rider,";  // Global definition of aCentaur.

// JScript code, omitted for brevity.
function antiquities()  // A local aCentaur variable is declared in this function.
{

// JScript code, omitted for brevity.
var aCentaur = "A centaur is probably a mounted Scythian warrior";

// JScript code, omitted for brevity.
  aCentaur += ", misreported; that is, ";  // Adds to the local variable.

// JScript code, omitted for brevity.
}  // End of the function.

var nothinginparticular = antiquities();
aCentaur += " as seen from a distance by a naive innocent.";

/*
Within the function, the variable contains "A centaur is probably a mounted Scythian warrior,
misreported; that is, "; outside the function, the variable contains the rest of the sentence:
"a horse with rider, as seen from a distance by a naive innocent."
*/  
It's important to note that variables act as if they were declared at the beginning of whatever scope they exist in. Sometimes this results in unexpected behaviors.
var aNumber = 100;
var withAdditive = 0;

withAdditive += aNumber;  // withAdditive is now 100.
tweak();
withAdditive += aNumber;  // withAdditive is now 200.

function tweak()  {
var newThing = 0;  // Explicit declaration of the newThing variable.
// The next statement, if it were not commented out, would generate an error.
// newThing = aNumber;
// The next statement assigns the value 42 to the local aNumber, implicitly declaring it.
aNumber = 42;
if (false)  {
    var aNumber;  // This statement is never executed.
    aNumber = "Hello!";  // This statement is never executed.
    }  // End of the conditional.
}  // End of the function definition.
The statement that is commented out attempts to assign the value of the local variable aNumber to the local variable newThing. It fails, despite the fact that a local aNumber variable is defined elsewhere in the function, and therefore exists throughout. The aNumber variable does not have any assigned value at the point where this statement occurs in the code, and is thus undefined.