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 trialHadi Farhat
10,678 PointsShouldn'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
231,275 PointsThe loop's block is exited and re-entered for each iteration, so the const gets disposed and re-created each time.
remedies
3,616 PointsIf 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.
richi ramos
593 Pointsrichi ramos
593 PointsHello 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
231,275 PointsSteven Parker
231,275 PointsHi 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.