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 Uses for Closures

Ratnadeep Debnath
Ratnadeep Debnath
42 Points

Confused when I tried

var buttons = document.getElementsByTagName('button');

function createHandler(name) {

console.log(name);

}

for(var i = 0; i < buttons.length; i += 1) { var button = buttons[i]; var buttonName = button.innerHTML; button.addEventListener('click', createHandler(buttonName)); }

//for the last solution I deleted the return function from the createHandler, now without clicking the buttons the console is giving answer. Can anyone help me?

Jonathan Cousins
Jonathan Cousins
7,508 Points

You forgot to wrap console.log in an anonymous function:

function createHandler(name) {
  return function() {
    console.log(name);
  }
}