JavaScript closure inside loops – simple practical example

Cover Image for JavaScript closure inside loops – simple practical example
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

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!


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello