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 trialTobiasz Gala
Full Stack JavaScript Techdegree Student 23,529 PointsHow const really work
I'm a little bit confused about const variables. I know that const is mutable when it comes to objects and arrays which means that you can update values and push new values but you cannot assign a brand new value to a const variable.
ul.addEventListener('change', (e) => {
const checkbox = e.target;
const checked = checkbox.checked;
});
Here is a part of the code from the video. As far as I understand, everytime even listener is triggered we reassign const variable... so why it works :)
1 Answer
Steven Parker
231,269 PointsThe scope (lifetime) of these variables is limited to each time the handler runs. They are being created and assigned only once each time, and are never re-assigned. When the handler function ends, the variables are disposed (no longer exist).
Michael Moffet
4,406 PointsMichael Moffet
4,406 PointsThe reason why it works is because those variables are being defined within the callback function on the event listener. Meaning that function runs every time the change event is detected.
A const cannot be reassigned within its own scope/context. So you couldn't reassign checkbox later on in that same example. But because a new callback function is being called every time the event fires (and therefore, new variables are being created), you don't run into an issue.