Languages
[Edit]
EN

JavaScript - closure inside loops - simple example

10 points
Created by:
Blessing-D
574

1. Problem overview

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:

// ONLINE-RUNNER:browser;

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.

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

A very common solution is to use an anonymous function and call it imidate to create clousure for a 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 the above example can be written in the 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

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. 

// 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 for var keyword - introduced in ES6 (ECMAScript 2015).

Merged questions

  1. JavaScript - problem with local variables inside loop

References

  1.  Array forEach method - MDC Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂

Join