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

Philip Kroupoderov
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Philip Kroupoderov
Front End Web Development Techdegree Graduate 21,641 Points

Question about the less < comparison

The for loop says:

for(var i = 0; i < buttons.length; i++)

He has buttons 0 to 9, meaning buttons.length is equal to 10. So why is he getting an alert dialog saying that "button 10" is pressed (because i < buttons.length which is the same as i < 10 should be 0 to 9, so it should be saying that button 9 is pressed and not 10). I also saw that when using let it did solve this problem. Could someone please explain all this:).

1 Answer

Steven Parker
Steven Parker
231,248 Points

With "var", the loop variable "i" is a global. So it is shared by all of the button handlers. While the handlers are being set up, the value of "i" counts up from 0 and when it reaches 10, the loop stops.

But then later, when any of the handlers accesses the value of "i", it is 10. It's the same for any button.

By using "let", each handler gets it's own copy of "i", which remains the same as when the handler was set up.