Variable Scope in JavaScript

Scope of the variable means extent within which it can be accessed. Based on the scope of the variable it can be defined as local variable or global variable.

Local Variable

If a variable is defined within a function then it can be accessed within that function block. Such variables is known as local variable. The scope of local variable is within the function block in which they are defined and cannot be accessed outside the function.

Example:Create a file scope.htm

<!DOCTYPE html>
<html>
<head>
<title>Variable Scope</title>
</head>
<body>
<div id="content"></div>
<script src='external.js'></script>
</body>
</html>

scope.js

function scopeTest()
{
	var i = 10; //local variable
	document.write(i); //prints local variable
}
scopeTest();

Global Variable

If a variable is defined outside all the functions then it can be used anywhere in code. Such variables is known as global variable.

Example: Update script file scope.js

var i = 11; //global variable
function scopeTest()
{
	var i = 10; //local variable
	document.write(i);
	document.write('<br />');
}
scopeTest();
document.write(i); //prints global variable
<< Functions Performing Operations >>