ES6 variable scopes in loops with closure

Ashwin Sureshkumar
Feb 7, 2016 · 2 min read
Image for post
Image for post

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.

The desired output of the above code is

But the actual output is

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.

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

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.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store