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 trialJames Steele
2,844 PointsWhy assign to const?
in this video we create a constant and assign the element to it by finding it by id.
const myHeading = document.getelementbyid('myheading');
and then we use that to add an eventlistener to then trigger a function if clicked.
myHeading.addeventlistener('click..........etc)
could we not just add the event listener directly?
i.e. document.getelementbyid('myheading').addeventlistener('click', () => {document.getelementbyid('myheading').style.color = 'red';}
What's the advantage of using a constant? Is it just to reduce the amount of typing because I find that I can just cut and paste from where I have written before and if I use a constant would I not have to keep referring to what that const was assigned to?
1 Answer
Steven Parker
231,275 PointsYou can select the element and add the listener at the same time, avoiding the variable. But since access to the element is going to be used again later (inside the handler), it addresses the "DRY" principle and also makes the code a bit easier to read.
// without variable, makes 2 calls to getElementById:
document.getElementById('myheading').addEventListener('click', () => {
document.getElementById('myheading').style.color = 'red';
});
// with variable (just one call):
const myHeading = document.getElementById('myheading');
myHeading.addEventListener('click', e => {
myHeading.style.color = 'red';
});