Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

JavaScript closure inside loops – simple practical example

var funcs = [];
// let's create 3 functions
for (var i = 0; i < 3; i++) {
 // and store them in funcs
 funcs[i] = function() {
 // each should log its value.
 console.log("My value:", i);
 };
}
for (var j = 0; j < 3; j++) {
 // and now let's run each one to see
 funcs[j]();
}

It outputs this:

My value: 3
My value: 3
My value: 3

Whereas I'd like it to output:

My value: 0
My value: 1
My value: 2


The same problem occurs when the delay in running the function is caused by using event listeners:

var buttons = document.getElementsByTagName("button");
// let's create 3 functions
for (var i = 0; i < buttons.length; i++) {
 // as event listeners
 buttons[i].addEventListener("click", function() {
 // each should log its value.
 console.log("My value:", i);
 });
}
<button>0</button>
<br />
<button>1</button>
<br />
<button>2</button>

... or asynchronous code, e.g. using Promises:

// Some async wait function
const wait = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms));
for (var i = 0; i < 3; i++) {
 // Log `i` as soon as each promise resolves.
 wait(i * 100).then(() => console.log(i));
}

It is also apparent in for in and for of loops:

const arr = [1,2,3];
const fns = [];
for (var i in arr){
 fns.push(() => console.log("index:", i));
}
for (var v of arr){
 fns.push(() => console.log("value:", v));
}
for (const n of arr) {
 var obj = { number: n }; // or new MyLibObject({ ... })
 fns.push(() => console.log("n:", n, "|", "obj:", JSON.stringify(obj)));
}
for(var f of fns){
 f();
}

What’s the solution to this basic problem?

Answer*

Draft saved
Draft discarded
Cancel
5
  • 8
    There is now such a thing as block scoping in JavaScript using the let and const keywords. If this answer were to expand to include that, it would be much more globally useful in my opinion. Commented Dec 27, 2017 at 3:12
  • @TinyGiant sure thing, I added some info about let and linked a more complete explanation Commented Mar 1, 2018 at 22:44
  • @woojoo666 Could your answer also work for calling two alternating URL's in a loop like so: i=0; while(i < 100) { setTimeout(function(){ window.open("https://www.bbc.com","_self") }, 3000); setTimeout(function(){ window.open("https://www.cnn.com","_self") }, 3000); i++ }? (could replace window.open() with getelementbyid......) Commented May 14, 2018 at 19:08
  • @nuttyaboutnatty sorry about such a late reply. It doesn't seem like the code in your example already works. You aren't using i in your timeout functions, so you don't need a closure Commented Jun 3, 2018 at 22:58
  • whoops, sorry, meant to say "it seems like the code in your example already works" Commented Jun 8, 2018 at 11:22

lang-js

AltStyle によって変換されたページ (->オリジナル) /