JavaScript - closure inside loops - simple example
In JavaScript, it is possible to create closure inside the loop in a 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:
xxxxxxxxxx
for(var i = 0; i < 5; ++i) {
var variable = 'variable-' + i;
setTimeout(function() { console.log(i + ' ' + variable); }, 100);
}
The reason why the loop prints only the last iteration results is the variables are overridden during each iteration - each iteration is executed without its own local scope - without its own closure. Bellow examples show how to solve the problem by adding closures for each iteration.
Approaches presented in this section create new closure for each iteration that allows to create local iteration variables.
A very common solution is to use an anonymous function and call it imidate to create clousure for a single iteration.
xxxxxxxxxx
for(var i = 0; i < 5; ++i) {
(function(i) {
var variable = 'variable-' + i;
setTimeout(function() { console.log(i + ' ' + variable); }, 100);
})(i);
}
Named functions make code more clear, so the above example can be written in the following way:
xxxxxxxxxx
function makeIteration(i) {
var variable = 'variable-' + i;
setTimeout(function() { console.log(i + ' ' + variable ); }, 100);
}
for(var i = 0; i < 5; ++i)
makeIteration(i);
Modern JavaScript introduced additional forEach
method that helps to iterate over arrays.
xxxxxxxxxx
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.
The let
keyword in modern JavaScript creates a copy of the variable for each iteration that makes it reusable after loop ended - setTimeout
function is a great example.
xxxxxxxxxx
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).