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 Using let with for Loops

Sahan Balasuriya
Sahan Balasuriya
10,115 Points

How does it know which button I clicked?

So I wondering how to the console know which button we clicked. The for loop loops till buttons.length so If I click button how will it know to stop at 5 so that i = 5. I can see the addEventListener but I'm assuming this is only for the alert message.

1 Answer

Steven Parker
Steven Parker
229,644 Points

The loop puts a separate listener function on each button, and each function contains the button number inside it. The loop finishes before any buttons can be clicked.

But later, when you click on a button, only the function that was attached to that specific button runs.

Sahan Balasuriya
Sahan Balasuriya
10,115 Points

still a it confused, could you show me the listener function

Steven Parker
Steven Parker
229,644 Points

The addEventListener takes another function as an argument. This other function is the one that will run when the button is clicked. The important point is that each button has it's own version of this function to run when it is clicked.

Brandon Lopez
Brandon Lopez
2,045 Points

Steven Parker- So are you saying each button is storing different data? (storing the unique function inside the button) And if so how does the button store data?

Steven Parker
Steven Parker
229,644 Points

The addEventListener function stores the function and any variables that are part of the function scope in system memory (not "inside the button"), and associates it with the button. See the documentation page for addEventListener for more details.

Steve Gallant
Steve Gallant
14,943 Points

This was so helpful. The video explains what happens but not really why. Thanks!