Search code examples
javascriptangularjsecmascript-6ecmascript-5

How to have block scopes in ECMAScript 5


When I was reading about ES 6 features, I found letwhich is used to create block scopes. This link has nice explanation on ES6 features and let statement. So how do developers create this block scopes in older versions of ECMAScript, like ES5.

The following code snippet explains let

var es = [];
for (var i = 0; i < 10; i++) {
  let c = i;
  es[i] = function () {
    console.log("Upcoming edition of ECMAScript is ES" + c);
  };
}
es[6](); // Upcoming edition of ECMAScript is ES6

What is the equivalent code in ES5?

Above code snippet without let, outputs 10 for i since it is in global scope.

var es = [];
for (var i = 0; i < 10; i++) {
  es[i] = function () {
    console.log("Upcoming edition of ECMAScript is ES" + i);
  };
}
es[6](); // Upcoming edition of ECMAScript is ES10

This link has ES6 equivalents in ES5 and it recommends to use IIFE for block scopes. But I am not sure, how to use IIFE in the current scenario.

Any help is greatly appreciated.

Thanks in advance.


Solution

  • it recommends to use IIFE for block scopes.

    In ES5, only calling a function creates a new scope. So "obviously", if you want to create a new scope (per iteration), you have to call a function. That's what an IIFE does: It creates a new function and calls it immediately.

    Any variable that would be block scoped (e.g. via let) would become a parameter of the function and initial values would be passed as arguments.

    Example:

    for (var i = 0; i < 10; i++) {
      (function(c) {
        es[i] = function () {
          console.log("Upcoming edition of ECMAScript is ES" + c);
        };
      }(i));
    }
    

    This is simplified of course and there may be cases that would require more elaborate solutions.