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 trial

JavaScript

Can someone help me understand this line of code?

When Guil is creating the event listener "change" for the checkbox, it seems he declares the checkbox as the target with this line of code:

const checkbox = event.target;

I've only previously seen him declare the targets with an "if" statement, for example:

if (e.target.tagName === 'INPUT').

Can someone help me understand the first example? It starts at 5:14 in the video.

https://teamtreehouse.com/library/rsvp-checkbox

1 Answer

andren
andren
28,558 Points

Actually he never specifies a target during the example you point to. The name of the constant is just there to make it obvious what it will end up storing. JavaScript itself never does anything special based on what you name something, he could have called it abc and the code would have worked identically.

The reason he doesn't specify a target is because there is no need to. The function he is writing is triggered when a change event is emitted from within the ul, the only element within the ul that can emit that event is the checkbox, so if the function runs you already know you are dealing with a checkbox.

If the page was changed so that there where multiple elements within the ul that could trigger a change event and you wanted different code to run based on the specific element, then you would need to use an if statement to check exactly what element triggered the event. Like he has done in previous tutorials.

This was perfect, thanks man.