Local and Global variable scopes in Javascript Functions
Tagged:

Javascript Functions are chunks of statements of javascript code which exist independently from the main script. These functions are executed only when called.

Local Variables
Variables that exist only inside a function are called Local variables. They have no presence outside the function. These variables are initialized only when a function is called. As soon as the execution comes out of the function, they die. The values of Local Variables cannot be changed by the main code or other functions.

Global Variables
Variables that exist throughout the script are called Global variables. The values of Global Variables can be changed anytime in the code and even by other functions.

Variable Scope
As Local variables exist only inside a particular function, they have Local Scope. However, Global variables are present throughout the script and their values can be accessed by any function hence, they have Global Scope.

Initializing a variable
If a Variable is initialized inside a function using the var keyword, it will have a local scope.
If a variable is initialized inside a function without var, it will have a global scope.
A local variable can have the same name as a global variable.

Local Variable Example:

var a = 5;

display_value();

function display_value()
{
var a = 50;
alert("Value of 'a' inside the function " + a);
}

alert("Value of 'a' outside the function " + a);

Click here to test the output of the code above

Code Explanation:
Here, a global variable a is declared first and assigned a value of 5. Then, a function display_value is called in which we again initialize a variable with the same name a. Note that we have used the var keyword inside the function. Hence, this variable will have a local scope. Once we come out of the function, the local variable no longer exists and the global variable takes over. The global variable a is unaltered in this case and it has its same initial value 5 even after the function has been called.

Global Variable Example:

var a = 5;

display_value();

function display_value()
{
a = 50;
alert("Value of 'a' inside the function " + a);
}

alert("Value of 'a' outside the function " + a);

Click here to test the output of the code above

Code Explanation:
In this case, all the other declarations are the same as the former except that we don't use the var keyword here when declaring a variable inside the function display_value, hence the global variable is used inside the function. The global variable a is now changed and it takes the new value that has been declared inside the function.