[Marked as a duplicate but would argue it is not; it addresses the same common example but the users posed different questions regarding it.]
I have been reading up on javascript closures but I am puzzled by two examples I found. The link below is from one of the stackoverflow articles I read and another snippet of code is from a javascript tutorial site.
Stackoverflow: How do JavaScript closures work? (Specifically Example 4).
Tutorial example:
<p>Counting with a local variable.</p>
<button type="button" onclick="myFunction()">Count!</button>
<p id="demo">0</p>
<script>
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
function myFunction(){
document.getElementById("demo").innerHTML = add();
}
</script>
In the code snippet above, a self invoking function is called once declaring and setting counter=0
. Then pressing the button triggers the add()
function and the counter increments, i.e 1 then 2 then 3..
.
My question is why? I know that the return function has access to the parent scope counter
but if the add()
function gets called again multiple times, should counter
not get reset multiple times back to 0
every time it is called? I believe the 'lexical environment' of each call is the same.
In Example 4 of the linked stackoverflow discussion, calling the function again reinitialized the variables as I would expect. Does this have something to do with var
being used to declare the function?
Tried also looking at the Mozilla documentation but it doesn't cover this type of scenario:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures