JavaScript - closure inside loops - simple example
1. Problem overview
In JavaScript it is possible to create closure inside loop in different way. It is caused because of historical reasones. In this article different ways how to create closure and local variables inside loops is presented.
Important note: before we will start, look at the below loop example without clousure. There were used
setTimeout
method. This method executes function after indicated time - in our example we used function that prints in console variables after 100ms.What do you think should be printed in console?
Loop without clousure:
// ONLINE-RUNNER:browser;
for(var i = 0; i < 5; ++i) {
var variable = 'variable-' + i;
setTimeout(function() { console.log(i + ' ' + variable); }, 100);
}
The reasone why loop prints only last iteration results is the variables are overridden during each iteration - each iteration is executed without own local scope - without own clousure. Bellow examples show how to solve the problem by adding closures for each iteration.
2. Classic for loop examples
Approaches presented in this section create new closure for each iteration that allows to create local iteration variables.
2.1. Anonymous function example
Verry common solution is to use anonymous function and call it imidatelly to create clousure for single iteration.
// ONLINE-RUNNER:browser;
for(var i = 0; i < 5; ++i) {
(function(i) {
var variable = 'variable-' + i;
setTimeout(function() { console.log(i + ' ' + variable); }, 100);
})(i);
}
2.2. Named function example
Named functions make code more clear, so above example can be written in following way:
// ONLINE-RUNNER:browser;
function makeIteration(i) {
var variable = 'variable-' + i;
setTimeout(function() { console.log(i + ' ' + variable ); }, 100);
}
for(var i = 0; i < 5; ++i)
makeIteration(i);
3. Array
forEach
method example
Modern JavaScript introduced additional forEach
method that helps to iterate over arrays.
// ONLINE-RUNNER:browser;
var array = ['a', 'b', 'c', 'd', 'e'];
array.forEach(function(value, index) {
var variable = 'variable-' + index;
setTimeout(function() { console.log(index + ': ' + value + ' ' + variable); }, 100);
});
Note: this approach appeared in ECMAScript 2015 - some browsers supported it before.
4. let
keyword example
let
keyword in modern JavaScript creates copy of variable for each iteration that makes it reausable after loop ended - setTimeout
function is great example.
// ONLINE-RUNNER:browser;
for(let i = 0; i < 5; ++i) {
let variable = 'variable-' + i;
setTimeout(function() { console.log(i + ' ' + variable); }, 100);
}
Note:
let
keyword creates for each iteration new local itaration variable - this is main difference forvar
keyword - introduced in ES6 (ECMAScript 2015).