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
177,538 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
177,538 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.