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 Getting Started With ES2015 Defining Variables With let and const Using let with for Loops

Hadi Farhat
Hadi Farhat
10,678 Points

Shouldn't const button throw an error after the first loop because It's already been defined?

for(var i = 0; i < buttons.length; i++) {
          const button = buttons[i];
          button.addEventListener("click", function() {
              alert("Button " + i + " Pressed");
          });
      }

Why const button = buttons[i] is not throwing an error? Constants can't be changed, so why does it work in this case?

2 Answers

Steven Parker
Steven Parker
229,744 Points

The loop's block is exited and re-entered for each iteration, so the const gets disposed and re-created each time.

Hello Steven, did you started learning at Treehouse? I saw you have a lot of points. Did you become a senior software architect thanks to the courses from this platform? did you get a job because of this learning ? Thanks.

Steven Parker
Steven Parker
229,744 Points

Hi Richi,

I was a software developer before I discovered treehouse, but I really have enjoyed using it to learn new skills and keep up to date on recent developments in evolving web technologies. One thing I did learn from scratch here is the Python language. I find the quality of the instruction combined with interspersed quizzes and challenges very effective for learning.

remedies
remedies
3,616 Points

If you had defined const outside the loop, and reassigned a value, you'd get an error, in this case, "const" is used each "reassignment" so that it is overwritten.