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

Crystal Vesely
Crystal Vesely
14,500 Points

In a loop, do variables reset after every iteration?

I am trying to understand when to use let vs const. When creating a variable in a loop, does the variable reset with each iteration? And what about nested loops? Do they follow the same rules? If they reset, it makes logical sense that you would use const for the variable, but if they don’t reset, then it makes sense to me that you would then need to use let.

1 Answer

Steven Parker
Steven Parker
231,275 Points

Variables defined with const and let have block scope. So if they are inside a set of braces (as commonly used when creating a loop), once that block ends (as it would at the end of each iteration) that variable is disposed. Then on the next iteration the variable is re-created. I suppose you could call that a "reset".

This makes const a good choice when the value will not be changed during the iteration.

Note that this doesn't apply to the variable used to control the loop, since it exists for the life of the loop and will get changed, so it cannot be const.

Crystal Vesely
Crystal Vesely
14,500 Points

Wow, thank you Steven. I’ve googled and researched on this topic, but your response has been the best in terms of helping me understand the mechanics so to speak of what is happening here! Having a fuller idea of the code helps me code better. I really appreciate your time!