'What is the difference in these two closures?

I have recently learnt there is a few ways to create a closure (not just returning a function from a function), but also referencing the function as a callback in an event listener. This creates a closure too which explains why you can call an innerFunction using an eventListener even after an IIFE has finished executing and has not returned anything.

I like to think the main power of a closure is that not only does it find a variable in an outer function to use in an inner function, but it also updates its value so it can be stored. For example, you can push into an array and update it inside an outer function or update a score set as a primitive on an outer function.

However, if you can create a closure via referencing a function via an event Listener then why can you not update a local variable every time a function is called via an event listener, see below for what I am trying to get at.

function increaseScore(){
   var score = 0;
   score ++;
   console.log(score); // console.logs one everytime the event occurs
                       // despite the event listener creating a
                       // closure for this funciton
}
document.addEventListener("click", increaseScore);

function addScore(){
  var score = 0;

  return function (){ // This too is a closure created in a different way
                      // and increases every time the event is called
   score ++;
   console.log(score); // 1, 2, 3, 4, etc. every time the event occurs
  }
}
var keepScore = addScore();
document.addEventListener("click", keepScore);

Why is this the case? They are both examples of closures, one via an event Listener, another via returning a function, but only the function that returns a function gets updated from its original value of zero and is held in memory for every time the function is called and the first function resets to zero every time, and therefore is only ever printing 1 to the console. I can’t find an explanation anywhere.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source