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 would you solve this problem before the `let` ?

Hi I'm learning the const and let for making variables. there is a block of code in one of the videos and I'm just curious as to how you would solve that problem in ES5? Here's the code. It's supposed to give an alert every time a button is pressed that says the number of the button. Example Button 1 was pressed or Button 2 was pressed and so on.

const buttons = document.getElementByTagName("button");

for (var i = 0; i < buttons.length; i++) {
    const button = buttons[ i ];
    buttons.addEventListener("click", function() {
        alert("Button " + i + " Pressed");
        })
}

1 Answer

Steven Parker
Steven Parker
243,658 Points

There's a couple of errors in this code, including the spelling of "getElementByTagName" (needs an "s") and the use of "buttons" (plural) where "button" (singular) is needed. But disregarding that for the moment:

Prior to "let", you might resolve the shared variable issue by creating bound functions for the handlers:

  button.addEventListener("click", function (n) {
      alert("Button " + n + " Pressed");
    }.bind(null, i)
  );

Thanks, Steven Parker for your lighting speed replies as usual but that is above my head, haven't gotten to that level yet, so, for now, I'm not understanding your reply. Will revisit it when I've absorbed more.

Steven Parker
Steven Parker
243,658 Points

Well, you asked! :smirk: But yes, that's advanced. Now that we have "let" it's much easier!

Touche! lol