I'm trying to understand the difference when adding a function to an event listener and what implications it has.
var buttons = document.getElementsByTagName('button');
for (i = 0, len = 3; i < len; i++) {
var log = function(e) {
console.log(i);
}
buttons[0].addEventListener("click", log);
}
for (i = 0, len = 3; i < len; i++) {
function log(e) {
console.log(i);
}
buttons[1].addEventListener("click", log);
}
The first button fires the console.log
3 times while the second only fires it once.
Why and what should you use when adding a function to an event listener in a normal situation?