Top community members
All Wiki Articles Create Wiki Article

Have you ever heard about encyclopedia for code?

What about: Wiki for Code project?

* because I've tried to share code and my solutions on different services and it was removed or I was unwelcomed
   - maybe it wasn't good place, but this one is.

if you think you have solution that can help someone, you are welcome to share this solution - Click here

JavaScript - closure inside loops - simple example

0 contributions
4 points

1. Problem overwie

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

Merged quastions

  1. JavaScript - problem with local variables inside loop

References

  1.  Array forEach method - MDC Docs
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey ūüĎč
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more