Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Using let with for Loops

Kieran Corcoran
Kieran Corcoran
11,188 Points

Further explanation needed: for loop const button = button[i];

The for loop in the video has the following line of code:

const button = buttons[i];

Each time through the loop the i values changes. How does this update the const button? From my understanding, you cannot assign a new value to a const

4 Answers

Ioannis Leontiadis
Ioannis Leontiadis
9,828 Points

Hello Kieran,

first of all below follows the script code from the video,

const buttons = document.getElementsByTagName("button");

for(var i = 0; i < buttons.length; i++) {
    const button = buttons[i];
    button.addEventListener("click", function() {
        alert("Button " + i + " Pressed");
    });
}

The for loop iterates through each button. The const button = buttons[i] variable is actually defined in each iteration and has a scope just inside this for loop.

Next, in each button we add an Event Listener or Handler which alerts the string "Button " + i + " Pressed" to the window. Note that because variable's i scope is global, when the click event of a button is triggered, i will have a value of 10 and the Listener or Handler function will alert "Button " + 10 + " Pressed".

Hope that helped!

What happens in this loop defined using the let keyword

for(let i = 0; i < buttons.length; i++) {
    const button = buttons[i];
    button.addEventListener("click", function() {
        alert("Button " + i + " Pressed");
    });
}

when I click on the button?

Isn't this loop always executed by default? How does the alert know that I clicked on button 5/6/7?

Thanks

You are absolutely right. You cannot assign a new value to a const. However, you can modify the existing value of a const. The existing value is const button = buttons[i] which gets modified within each loop by the value of i.

The goal of the loop is to assign a click event listener to the button const. That event listener is set to alert what button is clicked. I couldn't get why the instructor would take this route. Then I remembered that the value of let is confined to scope. Each loop has it's own scope (this is the main point to remember) and has it's own local copy of i. So on the second iteration, i = 2 and the loop is adding a click event listener that says "Button 2 is Pressed" to only the second button. The third button gets a click event listener that says "Button 3 is Pressed". And it continues until the 10th button.

With the var, the value of i is global. Each loop shares the same value of i. You aren't assigning a localized version of i. In that click event listener, the value of i will change with each iteration through the loop. You are pretty much saying "Button [whatever the value of i] is Pressed". By the time you click the button, i = 10.

I hope that explains it. For a second, I struggled receiving this point. I recommend you focus on the fact that each loop has it's own scope and let gives each iteration it's own value of i.

I also recommend the instructor to spend a little more time breaking down what is happening in this loop so that the video is not so confusing.

Your point is well taken. Additionally, from Kyle Simpson's You Don't Know JavaScript: Scope and Closures p. 38 —

Not only does let in the for loop header bind the i to the for loop body, but in fact, it rebinds it to each iteration of the loop, making sure to reassign it the value from the end of the previous loop iteration.

Excellent explanation, now i understand the logic

armand Rodriguez
armand Rodriguez
7,830 Points

Thank you so much, this really has cleared something I've been a little confused about for a while now. I've always the understanding of the scope let, i just didn't understand it in this context, but you cleared it up nicely!

Thanks very much, this is a great response and it cleared my confusion. That said, what is the point of declaring the button variable as 'const' if it's value will be continually updated? Wouldn't 'let' be more appropriate?

Mickey G If you declare button with let then you are reassigning it with every loop. The goal is not to reassign but to modify button.

The loop will only run until i = 10, then it will break... on each cycle the event listener is assigned to the button with a string that concatenates the local value of i (meaning the value of i at the moment 0,1,2,3 etc), before this wasn't the case due to the fact that var i had a global scope, so every event listener was accessing the same value of i, which at the end of the loop was i=10

You can find more details about let and var scope in the link bellow. Hope this helps!

http://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable

Yeah I got confused by this one. Thanks for the stackoverflow link, that's a great explanation. For anyone wanting a refresher on scope I found this YouTube video that really helped me! https://www.youtube.com/watch?v=SBwoFkRjZvE

best answer is in this thread