JavaScript closure inside loops – simple practical example
JavaScript Closure Inside Loops – Understanding the Problem
JavaScript closures inside loops can be a bewildering concept for many developers. The common issue arises when you try to create closures in a loop, and the closures access variables outside their scope. In most cases, you'll find that the value of the variable accessed inside the closures is not what you expect it to be.
Let's take a look at a practical example to understand this problem better.
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]();
}
This code snippet should output:
My value: 0
My value: 1
My value: 2
However, the actual output is:
My value: 3
My value: 3
My value: 3
This problem occurs because the closure created inside the loop does not capture the current value of i
at the time of creation. Instead, it captures the reference to i
, which is shared among all the created closures. As a result, when the closures are executed later, they all access the final value of i
, which is 3.
This problem can also occur when using event listeners or asynchronous code, as shown in the examples below.
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);
});
}
// ... 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 };
fns.push(() => console.log("n:", n, "|", "obj:", JSON.stringify(obj)));
}
for(var f of fns){
f();
}
In each of these examples, you'll notice that the expected values are not logged to the console. Instead, the closures access the final values of the variables involved.
🤔 What's the Solution?
The solution to this problem lies in creating a new scope for each iteration of the loop using an immediately-invoked function expression (IIFE) or using the let
keyword instead of var
in modern JavaScript.
Let's modify the initial code snippet to demonstrate the solution:
var funcs = [];
for (var i = 0; i < 3; i++) {
funcs[i] = (function(num) {
return function() {
console.log("My value:", num);
};
})(i);
}
for (var j = 0; j < 3; j++) {
funcs[j]();
}
Now, the output will correctly be:
My value: 0
My value: 1
My value: 2
By creating a new scope using an IIFE, we ensure that each closure captures its own copy of the num
variable, which is the value of i
at the time of creation.
Alternatively, using the let
keyword in modern JavaScript automatically creates a new block scope for each iteration of the loop. Here's how the modified code snippet looks using let
:
var funcs = [];
for (let i = 0; i < 3; i++) {
funcs[i] = function() {
console.log("My value:", i);
};
}
for (var j = 0; j < 3; j++) {
funcs[j]();
}
The output remains the same:
My value: 0
My value: 1
My value: 2
Now, you can apply these solutions to your event listeners, asynchronous code, for in
loops, and for of
loops to ensure the expected values are accessed inside the closures.
🎉 Conclusion
Understanding JavaScript closures inside loops is crucial to avoid unexpected behavior. By creating a new scope for each iteration using an IIFE or using the let
keyword, you can ensure that closures capture the correct values from their respective iterations.
So, next time you encounter a problem like this, remember to scope it right! Happy coding! 😊
👉 Do you have any other interesting JavaScript problems you'd like us to dive into? Share it in the comments below and let's solve them together!