DEV Community

kheersagar parja
kheersagar parja

Posted on

Block scope Vs Global scope var, let, const !!!

const a = 1;
let b = 2;
var c = 3;

if(true){
  const a = 10
  let b = 20
  var c  = 30
  console.log('Inside Block value of a = ' ,a ) 
  console.log('Inside Block value of b = ' ,b ) 
  console.log('Inside block value of c = ' ,c ) 
}
console.log('Outside Block value of a = ' ,a ) 
console.log('Outside Block value of b = ' ,b ) 
console.log('Outside block value of c = ' ,c ) 
Enter fullscreen mode Exit fullscreen mode

Output

Inside Block value of a =  10
Inside Block value of b =  20
Inside block value of c =  30
Outside Block value of a =  1
Outside Block value of b =  2
Outside block value of c =  30
Enter fullscreen mode Exit fullscreen mode

Why did value of a and b are unchanged outside the block??

The answer is let and const are block scope.

When Execution is in Line no. 1

var c is allocated memory in Global Scope whereas a and b are allocated memory in different scope.

When Execution reached to Line no.6

Values of variables are assigned but, a new scope can been seen, Block Scope where again a and b are allocated memory.

When Execution reached to line no. 9

Variables values are assigned in block scope and we can notice Script scoped a and b is not changed but global scoped variable c is changed to 30.

When Execution reached to Line no. 13 outside if block

Work of block scope is done and variable a and b values remains unchanged whereas value of c is changed.

Top comments (0)