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

What's the difference between reassigning a value to a variable and creating multiple 'local' copies?

.

2 Answers

Steven Parker
Steven Parker
231,248 Points

The re-assignment of a variable doesn't create copies of it, it simply changes the value it is holding.

The "copy" process is related to the scope of the variable. For a "var" variable, the variable shares the scope of the surrounding code, so that variable is "shared" and changes made in one place will be seen from the other. But a "let" variable is block scoped, so inside a loop each iteration has a different scope and gets a copy of the variable.

The difference might not be noticed except in cases like in the video, where the reference in the loop isn't used until after the loop has changed the value of the index.

.