Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closures versus ES6 Let

Tags:

javascript

Trying to print series of numbers inside for loop using closures and with let:

Consider the following example:

  for(var i=1; i<10; i++){      
      setTimeout(function(){
        document.write(i);
      }, 1000);
  }

Output is:

101010101010101010

With Closures:

  for(var i=1; i<10; i++){    
    (function(x){      
      setTimeout(function(){
        document.write(x);
      }, 1000);      
    })(i);
  }

Output is:

123456789

Without closure, just using ES6 let:

 for(let i=1; i<10; i++){      
      setTimeout(function(){
        document.write(i);
      }, 1000);
  }

Output is:

123456789

Trying to understand if we still need closures using IIFE blocks moving towards ES6?

Any good example if we really need closures with ES6?

like image 989
Mithun Shreevatsa Avatar asked Jan 27 '17 11:01

Mithun Shreevatsa


People also ask

What is es6 closure?

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.

When should closures be used?

Closures are frequently used in JavaScript for object data privacy, in event handlers and callback functions, and in partial applications, currying, and other functional programming patterns.

What is closures and disadvantages of closures?

Disadvantages of closures There are two main disadvantages of overusing closures: The variables declared inside a closure are not garbage collected. Too many closures can slow down your application. This is actually caused by duplication of code in the memory.

What are the benefits of using closures?

Closures have to do with how javascript is scoped. To say it another way, because of the scoping choices (i.e. lexical scoping) the javascript designers made, closures are possible. The advantage of closures in javascript is that it allows you to bind a variable to an execution context.


1 Answers

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('');
})();
like image 112
Noam Manos Avatar answered Oct 14 '22 10:10

Noam Manos