ES6 variable scopes in loops with closure

Ashwin Sureshkumar
2 min readFeb 7, 2016

--

EcmaScript 6 is increasingly being adopted by many open source libraries and companies which use ES6 or Typescript (superset of ES6).

I am hoping to write small byte sized posts during my learning journey to share my experience.

In ES6, block scoped variable declaration was introduced with the keyword let

According to MDN,

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

Below is a simple code snippet which should console log out the value of i after 100ms on each loop.

for(var i = 1; i <= 5; i++) {   setTimeout(function() {
console.log('Value of i : ' + i);
},100);
}

The desired output of the above code is

Value of i : 1
Value of i : 2
Value of i : 3
Value of i : 4
Value of i : 5

But the actual output is

Value of i : 6
Value of i : 6
Value of i : 6
Value of i : 6
Value of i : 6

The above result is because, var defines variable globally, or locally to an entire function regardless of block scope.

To fix the issue in ES5, we used Immediately Invoked Function Expression (IIFE) to capture the state of variable.

for(var i = 1; i <= 5; i++) {

(function(i){
setTimeout(function(){
console.log('Value of i : ' + i);
},100);
})(i);
} Output:
Value of i : 1
Value of i : 2
Value of i : 3
Value of i : 4
Value of i : 5

With the introduction of let which defines the variable in block scope, the above code can be refactored as shown below

for(let i = 1; i <= 5; i++) {

setTimeout(function(){
console.log('Value of i : ' + i); },100);}Output:
Value of i : 1
Value of i : 2
Value of i : 3
Value of i : 4
Value of i : 5

let creates a variable declaration for each loop which is block level declaration. So basically it creates a scope within { }.

This is a simple introduction to block level scoping and usage of let. There is more practical uses and techniques using let which I am hoping to capture in future posts.

--

--