Wednesday, August 24, 2016

Block level scoping in JavaScript

Block level scoping in JavaScript

If you are familiar with JavaScript. If you are working as FE developer then must be aware that JavaScript has functional level scoping not block level scoping as in C family languages.

Now, from ES6 JavaScript introduces let keyword. "var" keyword is still there which will function in same manner as it is currently. Using let keyword you can declare one variable inside one block and its scope will be in that block only as block level scoping in C family languages.

For example
// using var only
function myFun(){
 var a=1;
 if(a>0){
  var b=2;
 }
 console.log(b);
}

myFun(); // 2

// using let keyword
function myFun2(){
 var a=1;
 if(a>0){
  let b=2;
 }
 console.log(b);
}

myFun2(); // Uncaught ReferenceError: b is not defined

In above example second function myFun2 gives error as let has block level scoping only and it is declared inside if block so it is not available out side if block.