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 trialJared Greenberg
6,887 PointsPassing a value into the event callback function.
So, I understand the use of closure with the createHandler function that we've created and also the difference in scope when using 'let' vs. 'var'. But why doesn't it work to just pass buttonName into the original callback function like this?
for(var i = 0; i < buttons.length; i += 1) {
var button = buttons[i];
var buttonName = button.innerHTML;
button.addEventListener('click', function(buttonName) {
console.log(buttonName);
});
}
Since it is a pass-by-value shouldn't the appropriate "button name" be assigned as the parameter for each respective callback function as the loop progresses? However with this scenario when I click on the buttons, nothing is logged to the console.
JASON LEE
17,352 PointsJASON LEE
17,352 PointsInside the
.addEventListener
thebuttonName
is the parameter infunction(buttonName)
, but you're using it like an argument. You can name parameters whatever you want, but the actual argument that got passed in is theevent
object which is built-in to theaddEventListener
method. Theevent
object has many properties, likeevent.target
which returns the HTML element, but has no relevance tobuttonName
variable in the use that it was intended. I'm a student learning as well, so someone correct me if I'm wrong.