0

[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

Beep
  • 23
  • 3
  • `add` is just called once. The anonymous function is called multiple times. – Jonas Wilms Jan 11 '18 at 16:02
  • `add` variable stores a result of calling _outer_ anonymous function (that does declare `var counter`). That outer function is called just once. Resulting function doesn't have `counter` declared inside it - it uses it from outside scope. – raina77ow Jan 11 '18 at 16:03
  • but when a button is pressed, isn't `add()` called each time? – Beep Jan 11 '18 at 16:04
  • You're correct, `add` is called multiple times. – raina77ow Jan 11 '18 at 16:04
  • @raina77ow i didn't know this; I thought `add` stores the entire contents of the function, and not just the `return ...` portion? – Beep Jan 11 '18 at 16:06
  • `add` is a variable that references this anonymous function: `function () {return counter += 1;}`. – Paul Jan 11 '18 at 16:09
  • The other anonymous function was called once at the start as an IIFE and its return value was assigned to `add`. – Paul Jan 11 '18 at 16:10

0 Answers0