Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
216,017 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.