How to know Variable Scope in Javascript

Variable Scope
Means:
1. Lifetime of variable
2. Place where the variable is available to use

On basis of variable scope, You can say
variables are local, global and window variable.

Variable Scope / Scope of Variable Javascript

Local variable:

This variable is used only inside the function. You can not use this
variable outside of the function or inside other functions.

Examples of Variable Scope:



function checkVariable(){
var value = 10;

/* variable value is only availabe for checkVariable function.

If you call outside of this function, then the output will be undefined. */
}

var value=5;
console.log(value); // output will be undefined.
// Let's check on the browser.

Local variable value is not available outside. When I create a variable outside of this function. It is available.

Global variable:

A variable declared outside of the function is available for the entire document.
This is a global variable.

Let's check by an example:



var a=23;
function checkVariable(){
alert("Global variable scope inside function "+a);
}

checkVariable();
alert("Global variable scope outside function "+a);

The global variable is available for the entire document.

Lets analysis some cases.

Can we change the value of a global variable from a function's local variable?
Let's try


var a = 5;
function updateGlobal(){
a=6; // updated value of a here
alert("Value of inside function: "+a);
}
updateGlobal();
alert("Value of outside function: "+a);

Let's see results on the browser:
You have seen that the value of a is updated from the function. But here variable
inside the updateGlobal function is not local. It is global because you haven't use a prefix like "var" here.

Now I am updating it to make is a local variable.


var a = 5;
function updateGlobal(){
var a=6; // updated value of a here
alert("Value of inside function: "+a);
}
updateGlobal();
alert("Value of outside function: "+a);

What do you think, What will be the output now?
Output:
Value of inside function:6
Value of outside function:5

Now you can see, you can not update the global variable by local variable.
If you want to update global variable from the function, you can only
update by a global variable.

Window variable:

This variable is similar to a global variable.
You always use 'window' as a prefix with a variable. for example

avascript]window.a = 5;

This 'window.a' a variable is available for the entire window. you use it inside/outside of any function.

Read also: Let Vs Var: Battle between modern javascript keywords

I have tried to explain, the scope of a variable in javascript. If you have
any query. You can comment, I will try to respond quickly.

Thanks and keep in touch.

Click here to check other Javascript operators.