Core JavaScript

Variable Scope

The scope of a variable is limited to the function where it is declared. Variables that are declared outside of a function have global scope. Inside of the region of the scope, a variable can be accessed before the variable is even declared.

The program below begins by printing the value of X, which is undefined initially. Next, X is assigned the value "Before the declaration". As indicated, this assignment is made before the variable is declared, illustrating that the variable exists before it is declared--the value is printed afterward. Then the variable is declared and assigned the value "Global" inside of an "if" code block to illustrate that the block does not limit the scope as it does in other languages. Then a function is defined with another X declaed inside of it; the variable is printed inside, before and after the declaration, to show that both refer to the local variable. Finally, the function F() is called and the variable is printed afterward to show that the function call did not affect the global variable.

VariableScope.html

<!DOCTYPE html>
<html>
<head>
    <title>XoaX.net's Javascript</title>
</head>
<body>
    <script type="text/javascript" src="VariableScope.js"></script>
</body>
</html>

VariableScope.js

// Access the variable before it is declared or assigned a value
document.writeln("Outside: " + X + "<br />");

// Assign the variable a value before it is declared.
X = "Before the declaration";

// Access the variable before it is declared.
document.writeln("Outside: " + X + "<br />");

// Declare the global variable inside an if block, but outside a function
if (true) {
	var X = "Global";
}

// A second version is declared and assigned inside a function
function F() {
	document.writeln("Inside: " + X + "<br />");
	var X = "Local";
	document.writeln("Inside: " + X + "<br />");
}

// Call the function to execute it.
F();

// Access the variable outside the function. This is the first global version.
document.writeln("Outside: " + X + "<br />");
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.