Variables scope in JavaScript

Understanding variables scope in JavaScript

 
Let's understand variables scope in JavaScript and how does it work.
 
Scope is basically used for managing the visibility and accessibility of variables from different part of program.
 

Global vs Local Scope

 
var myglobalscope = "global scope";

function localScopeFun(){
	localScope="local scope";
	console.log(localScope); // local scope
	console.log(myglobalscope); // global scope
}

localScopeFun();
console.log(localScope); // local scope
console.log(myglobalscope); // global scope
 
So in the above example localScope variable declared without 'var' keyword will be treated as a global variable. So be careful while creating any variable inside function and you want to refer those variable locally only. Use var keyword to keep the variable scope limited to that function.
 
And in the same code if we use 'var' keyword for 'localScope' variable then accessing that variable outside of the function will raise javascript error.
 
var myglobalscope = "global scope";

function localScopeFun(){
	var localScope="local scope";
	console.log(localScope); // local scope
	console.log(myglobalscope); // global scope
}

localScopeFun();
console.log(localScope); // ReferenceError: localScope is not defined
console.log(myglobalscope); // and due to error this statement will not execute. 
 

Block level Scope

 
In JavaScript any variable declared with var keyword do not have block level scope like other programming language (C, C++, Java etc.). Let's understand this by example.
 
var x =2;
{
   var x  = 3;
   console.log(x); // 3
}

console.log(x); //3
 
You are seeing the output of variable x out of the block is 3, because variable x declared within the block have the same scope as the variable x declared outside of the block.
 
Note**: ECMAScript version 6 support block level scope by using 'let' keyword.
 
let x =2;
{
  let x  = 3;
  console.log(x); // 3
}

console.log(x); //2

Scopes in For and While loop

 
Any variable part of for or while loop survived after a loop and again this is because of their scope is function not block.
 
for(var i=0; i<5; i++) { }

alert(i); // 5;

while(i < 10){
	i++;
}

alert(i); //10;
Hope this is useful and have given you an understanding of scopes in JavaScript.
 
Keep Reading and Keep learning.