Scope of Variables in Javascript
In this article, we will discuss the scope of variables in javascript which is local scope vs global scope. The scope indicates the “accessibility” and “visibility” of variables (i.e. life of a variable). Javascript variables are of local scope (function scope) or global scope.
Difference Between Local and Global scope
Local Scope | Global Scope |
---|---|
Any variable declared inside a function is considered as in local scope. | Any variable not declared inside a function is considered as in global scope. |
It can be accessed only inside that function where it is declared. Local variables will be available only in the function execution. |
It can be accessed anywhere in the script |
That means local variables are created as soon as the control enters the function body and deleted as soon as the control exits the function body. | Global variables will be available throughout the script execution |
Example for the scope of the variable
var a = 10; //Global Scope
function display(){
document.write(" (global a =", this.a, "<br/>"); //a=10
var a= 20; // local Scope
document.write("local a =", a, "<br/>"); //a=20
}
display();
/*
Output:
global a =10
local a =20
*/
In the above code, the variable “a” has the value “10”, it is a global variable because this variable is not declared inside the function. Then we have a function display, inside the function, we print “a’ variable using this method. The “this” method is used to access an outside variable. And create another variable “a”, it is a local variable because this variable is declared inside the function. Then we print variable “a” and call the display() function. So, the output will display a=10, and a=20 because The variable ‘a’ has two values 10 and 20.