JS: Accessibility of Vriables in function
, conditions & loops | JavaScript
JavaScript Variable Scope
Variable Scope is the accessible region of a variable, a function or class in a program. A variable defined in a function
, if
block, swith
case
statements, for
loop, while
loop and do
while
loop blocks, is inaccessible outside.
function test()
{ //scope of local1 starts
var local1 = 10;
console.log(local1); //accesible and will be printed on function call
} //scope of local1 ends
test();
console.log(local1); //error
10
Uncaught ReferenceError: local1 is not defined
Variable scope is the life time in terms of accessibility of an identifier (variable or function name) within the JavaScript program.
Different variables has different scope. Scope depends where the variable was declared and keyword used to declare. Two variables declared with var
and let
may have different scope.
Types of JavaScript variable Scope
- Global scope
- Local scope
- Function scope
- Block scope
Global Scope
Variables declared outside a functions are globally accessible i.e. accessible thought the program by any statement or line of code. This is know as Global Scope
var topic;
function init(){
topic = 'Global Warming';
console.log('assigned topic');
}
function show(){
console.log('topic:', topic);
}
init();
show();
Global Scope through function
Variable assigned a value in a function without declaration var
become Global Variable
function init(){
topic = 'Global Warming';
}
function show(){
console.log('topic: ', topic);
}
init();
show();
topic: Global Warming
JavaScript must reach the point of initialization by calling the function. If show()
is called before init()
, the error will be raised as topic is unknown.
But if add var
with the topic make its scope local.
function init(){
var topic = 'Global Warming';
}
function show(){
console.log('topic: ', topic);
}
init();
show(); //error
Uncaught ReferenceError: topic is not defined
Strict Mode
Strict Mode is the solution to avoid Global Scope though function. Add "use strict"
at the top of the JavaScript file:
"use strict"
//regular code here
or at top of the function
function strict(){
"use strict"
//regular code here
}
Please refer the Strict Mode Chapter for details.
Local Scope
Variables declared within a function are locally accessible i.e. accessible within that function only. This is know as Local Scope
function init(){
var topic = 'Global Warming';
}
function show(){
console.log('topic:', topic);
}
init();
show();
Local scope variables are one of the following types:
- Function scope
- Block scope
Function Scope
Variables declared with var
have function scope. var
makes variable accessible through the function no matter where they are declared in the function
function test()
{ //scope of p starts
var p = 10;
console.log(p); //accessible
} //scope of p ends
test();
console.log(p); //error
undefined
var Hoisting
Variables declared with var
keyword are accessible before declaration at the top of its scope: this is called hoisting. In the following example console.log(p)
is called before var p = 10
. console.log(p)
didn't caused error, but without error. This is due to Hoisting feature. Hoisting works if the variable declared with var
. Hoisting does not work with let
and const
declaration.
function test()
{ //scope of p starts
console.log(p); //p accessible here but value is undefined
var p = 10; //p has value 10
} //scope of p ends
test();
undefined
Since the scope of p starts at the top of the function test()
, that's why p does not throw error ReferenceError: p is not defined.
Variables declared in function withvar
are accessible before their declaration point but not their value. Therefore, they will not generate error when accessed but will haveundefined
value until initialized.
var accessible
var
behaves differently than oth
var v = 'At Global'; //set global v
function test()
{
v = 'In function'; //change global v
if(true)
{
v = 'In if'; //change global v
}
}
test();
console.log(v);
In if
The code has just one declaration, and the function test()
use the global variable v that's why the global variable keeps the value changed.
Just declaring v within function will change the result:
var v = 'At Global'; //set global v
function test()
{
var v = 'In function'; //change global v
if(true)
{
v = 'In if'; //change global v
}
console.log(v);
}
test();
console.log(v);
In if
At Global
The code has two declarations, and the function test()
now use the its own local variable v that's why the global variable not changed where as changes made to local declaration of v
Lets make another little change, move the declaration var
of v within if block. This change, changes the result?
var v = 'At Global'; //set global v
function test()
{
v = 'In function'; //change global v
if(true)
{
var v = 'In if'; //change global v
}
console.log(v);
}
test();
console.log(v);
In if
At Global
No change! Due to function scope of var
, v is hoisted at the top of the function accessible. So the effect is the same. as of the previous code.
block scope
Variables declared with let
or const
have block scope. The scope starts with the makes variable accessible through the function no matter where they are declared in the function
Block Scope accessibility
Block scope variables are not accessible until there declaration. Despite the var
, let
and const
don't result undefined
value rather error.
function test()
{
console.log(p); //error
let p = 10; //scope of p starts
} //scope of p ends
test();
Uncaught ReferenceError: Cannot access 'p' before initialization
Local scope picture
Following code depicts the complete picture of local scope and its accessibility.
function test()
{ //scope of p starts
var p = 10;
if(true)
{ //scope of q start
let q = 1;
} //scope of q ends
} //scope of p ends
console.log(p); //error
ReferenceError: p is not defined
JavaScript Scope priority
Among global scope, function scope and block scope, the inner most nested declaration has the higher priority.
var s = 'Global';
function test()
{
var s = 'Function';
if(true)
{
let s = 'Block';
console.log(s); //shows 1st
}
console.log(s); //shows 2nd
}
test();
console.log(s); //shows 3rd
Block
Function
Global
In case we there is an argument in function test
parameter, then priority will be this way:
- Block
- Function
- Parameter's Argument
- Global
var s = 'Global';
function test(s)
{
if(true)
{
let s = 'Block';
console.log(s); //shows 1st
}
console.log(s); //shows 2nd
}
test('parameter');
console.log(s); //shows 3rd
Summary
- JavaScript variable accessible means can use a value or replace old value with new value
- JavaScript variables declared or initialized outside functions are global variables
- JavaScript global variables are accessible throught the program
- JavaScript variable declared within a function is local variable
- JavaScript variable within a function without declaration keyword become global variable
- JavaScript allows same identifier name at different scopes
Conclusion
Following code is the a snapshot of JavaScript variable scope.
var g = 1; //global scope
function test()
{ //scope of local1 starts
if(true)
{
var local1 = g + 10; //g accessible
var local2 = g + 20; //g accessible, scope of local2 starts
}//scope of local2 ends
console.log(local1); //local1 accessible
console.log(local2); //error
} //scope of local1 ends
console.log(g); //g accessible
console.log(local1); //error
g is accessible everywhere (in the program including functions) since it is not declared in any function, hence g is global scope.
local1 is declared with var
in a function, hence its is accessible within function test() has function scope.
local2 is declared with let
in a function, hence its accesible within its block (if
blcok in this example) called block scope.