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?
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.
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.
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.
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.
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('');
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With