Why eventlistener click requires a return function to work

//This works

for (var i = 0; i < 5; i++) {
  var btn = document.createElement('button');
  btn.appendChild(document.createTextNode('Button ' + i));
    btn.addEventListener('click', (function(i) {
        return function() {console.log(i)};
    })(i));
  document.body.appendChild(btn);
}

//This doesn't work

for (var i = 0; i < 5; i++) {
  var btn = document.createElement('button');
  btn.appendChild(document.createTextNode('Button ' + i));
    btn.addEventListener('click', (function(i) {
        return console.log(i);
    })(i));
  document.body.appendChild(btn);
}

http://jsfiddle.net/sjzLhur0/

Could someone tell me why the second example doesn't work? Why would you need to return a function?

Answers


Because you are using an IIFE, we can substitute it with its return value. So the first example is similar to

btn.addEventListener('click', function() {console.log(i)});

and the second example is similar to

 btn.addEventListener('click', console.log(i));

(the actual value of i is irrelevant to the problem at hand)

addEventListener expects a function to be passed as second argument but the second example doesn't pass one. It passes the return value of console.log, which is undefined. So there is nothing to executed on click.

Why eventlistener click requires a return function to work

Note that the event listener doesn't return a function. In your first example, function() {console.log(i)} is the event handler. The outer function (function(i) { ... }(i)) is just a function that generates the event handler.


So in the essence you are subscribing to an event which is going to happen somewhere in the future (once you click the button).

In the first (working) example, when you create an IIFE and the result of IIFE is an function then when event happens there is a callback (returned function) which is called to generate the desired result.

In the second (non-working) example you are creating an IIFE which is executed immediately so you get something as:

btn.addEventListener('click', undefined);

As the second parameter is not a function (as required) there's nothing to execute once you press the button and callback is fired.


Because the first example is not really returning a function. There is nowhere for your function to return anything to, so is can't return anything. In your first example, it is returning a function, but that function is really just calling console.log(i);. Your second example would work if you said console.log(i); as opposed to return console.log(i);


Need Your Help