Tuesday, September 11, 2018

How scope behaves in JS (let, block scope)


scope refers to the lifecycle of the variable, ie, where in the code its visible and how long

Understand "What is not a block scope"
curly braces doesnt mean block scope,
{
 // its not a block scope, but a global scope
 var a = "mytest"
}
console.log(a) // prints mytest

var a inside block overrides var a in function scope, so not a block scope

function myfun() {
  var a = "function scope";
  for (var i = 0; i < 10; i++) {
    var a = "override";
  }
  console.log(a)
  // prints "override" as said the curly braces don't signify block scope.
}


So how to declare block scope variable ?
ImmediatelyInvokedFunctionExpression (IIFE)


(function () {
  var a = "correct block scope";
})()

ie, the above myfun becomes


function myfun() {
  var a = "function scope";
  for (var i = 0; i < 10; i++) {
    (function () {
      var a = "right block scope";
    })()
  }
  console.log(a) // prints "function scope" .
  // because variable a inside IIFE is in block scope.
}

With ES6 we have "let" keyword, use inplace of "var" keyword. This creates a variable with block level scope. So myFunc becomes


function myfun() {
  var a = "function scope";
  for (var i = 0; i < 10; i++) {
    let a = "right block scope";
  }
  console.log(a) // prints "function scope" .
}

var a is only visible between the for-loop and not outside the loop

Ex:

var myFuncArray = [];
for (let i = 0; i < 5; i++) {
  myFuncArray.push(function(){
    console.log(i);
  })
}

myFuncArray.forEach((myfun) => {
  myfun(); //prints 0...4
});

for more JS quirks click here...