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

How does the terminal determine which "i" value to display on click?

I am working through the "Defining variables with let and const" workshop. We have been provided with the following code (I added in the console.log functions to try to determine what is happening):

<html>
  <head>
    <title>buttons - let and Const</title>
  </head>
  <body>
    <h1>Buttons</h1>
    <button>Button 0</button>
    <button>Button 1</button>
    <button>Button 2</button>
    <button>Button 3</button>
    <button>Button 4</button>
    <button>Button 5</button>
    <button>Button 6</button>
    <button>Button 7</button>
    <button>Button 8</button>
    <button>Button 9</button>
    <script>
      const buttons = document.getElementsByTagName("button");

      for(let i = 0; i < buttons.length; i++) {
          const button = buttons[i];
          console.log(i); // I added this
          button.addEventListener("click", function() {
              alert("Button " + i + " Pressed");
              console.log(i); // And this
          });
      }
    </script>
  </body>
</html>

By adding the console.log functions, I was able to see that the loop is executed once, as each button number is logged to the console.

My question is, how does the console determine which button we are clicking on to display the appropriate value of "i"?

Thank you in advance!

2 Answers

Jesus Mendoza
Jesus Mendoza
23,289 Points

Hey Cory,

Each time the loop executes you are adding a new event listener to each button, so, when you click a button, the event listener to that specific button is triggered distinguishing it from others.

Jesus,

Ahhh, that entirely makes sense. Thank you!

Is there a way to see the DOM with those event listeners added? I would like to see what this looks like under the hood if possible.