Closures versus ES6 Let

Here's a good explanation by Kleo Petrov -

Do ES6 Modules make the case of IIFEs obsolete?

IIFE was one of the most used patterns in the ES5, as functions were the only way to declare a scoped block of code. In ES6, instead of using IIFE, we can use modules:

// myModule.js

let counter = 0;

export function increment() {
    counter++;
}    

// logic.js

import {increment} from 'myModule.js';

increment();

The only case, where you may want to use an IIFE in ES6, is with an immediately-invoked arrow functions, that requires more than a single expression, for example:

const SENTENCE = 'Hello world, how are you?';
const REVERSE = (() => {
    const array  = [...SENTENCE];
    array.reverse();
    return array.join('');
})();

let binds names in the block scope for the variables declared with it. You can read the semantics in the standard document.

If you have let, use it. Otherwise use IIFE or rewrite the code to avoid needing either.


One simple example of using closures, that I could remember, is a counter:

function makeCounter() {
  let currentCount = 1;

  return function() { 
    return currentCount++;
  };
}

let counter = makeCounter(); 


console.log( counter() ); // 1
console.log( counter() ); // 2
console.log( counter() ); // 3

This particular use case when you want to use the value of a variable which is reassigned in a loop at each iteration is indeed simplified with the new Es6 block scoping.

There is a very good review of the behavior of this in the latest N. Zachas book available on github (the whole book is a very good read and you should probably buy it if you intend to use it as a main reference).

As for your example using the new syntax is probably the new best practice because it results in the expected behavior, whereas the old for(var i = 0; i < length; i++){} syntax was confusing.

Keep in mind however that you will probably want to transpile your code to es5 using either Babel or Tracer. In this case, the way those tools use to simulate block scoping is by using closures. So you probably should understand the pattern anyway for sake of completion and debugging purposes.

Example of transpilation from the example in the book here

Tags:

Javascript