Quick Tip -  Use let with for Loops in JavaScript

Quick Tip - Use let with for Loops in JavaScript

The other problem using let and const will fix is with our for loop.

This is something that you probably have all run into with your regular for loop, like one that will count from zero to nine:

for(var i = 0; i < 10; i++) {
  console.log(i);
}

Problems that arise here are two things:

First of all, if I type i into the console, it returns 10. We have this global variable that has leaked into the window, or into a parent scope, which is not something we necessarily want. It's just a placeholder value that we need to work inside of this loop.

Second of all, maybe you had something that's going to run after some bit of time, an AJAX request, or, for this case, I going to mark it up with a setTimeout() and that function is going to run after one second:

for(var i = 0; i < 10; i++) {
  console.log(i);
  setTimeout(function() {
    console.log('The number is ' + i);
  },1000);
}

If we run this, all of them are 10. The reason that we have that is because, console.log(i) will run immediately and reference whatever i is. That runs immediately at console.log itself.

However, after one second, this entire loop has already gone through every iteration that it needs to and the variable i here is being overwritten every single time.

The problem with that is that by the time the first setTimeout() runs, i is already at 10, and we don't have any way to reference it.

If you had an AJAX request where you are looping through a few of them, there isn't any way without an IFFE to reference what the i variable was when it ran, not what it currently is after the loop.

One quick way we can fix that is if we just change var to let:

for(let i = 0; i < 10; i++) {
 console.log(i);
 setTimeout(function() {
   console.log('The number is ' + i);
 },1000);
}

What do we know about let? It's block-scoped. We have curly brackets in the for loop. If you run it now, after a second we'll log zero through nine. We're not getting 10, 10 times. We getting it as it was declared each and every time.

As a note, you couldn't use a const for this because it needs to overwrite itself, and you can't assign the same variable twice. When we use let, it's going to scope i to our curly brackets.

Find an issue with this post? Think you could clarify, update or add something?

All my posts are available to edit on Github. Any fix, little or small, is appreciated!

Edit on Github

Syntax Podcast

Hold on — I'm grabbin' the last one.

Listen Now →
Syntax Podcast

@wesbos Instant Grams

Beginner JavaScript

Beginner JavaScript

A fun, exercise heavy approach to learning Modern JavaScript from scratch. This is a course for absolute beginners or anyone looking to brush up on their fundamentals. Start here if you are new to JS or programming in general!

BeginnerJavaScript.com
I post videos on and code on

Wes Bos © 1999 — 2024

Terms × Privacy Policy