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

About the different values of 'i'

I get that the function in the event handler gets evaluated at the moment the user clicks the button, not when the for loop runs, and that's why the i variable, when declared with var, equals 10.

When using let each event handler gets a refence to its very own i, each with a different value. But why do they still exist when the button is pressed? I mean, I thought variables declared with let inside a loop only exist inside that loop. Then why after the loop ends, and the button gets clicked, those ten different i variables still can be accessed by the event handler?

Or is it that the function in the event handler gets a hard-coded value in the code, like

"button" + 5 + "has been pressed";

I don't get that part. Thanks!

Steven Parker I really understand your answers :D

1 Answer

Steven Parker
Steven Parker
231,275 Points

:bell: Hi, I got alerted by your tag.

As I understand it, a variable is only disposed of when all scopes it is available to cease to exist. While the loop itself may have completed, the loop created a handler function to which the variable is still available, so it continues to exist for that function.