0
<!DOCTYPE html>
    <html>
    <body>

    <p>Counting with a local variable.</p>

    <button type="button" onclick="myFunction()">Count!</button>

    <p id="demo">0</p>
    <p id="try">try</p>

    <script>
    var add = (function () {
        var counter = 0;
        document.getElementById("try").innerHTML = counter;
        return function () {return counter += 1;}
    })();

    function myFunction(){
        document.getElementById("demo").innerHTML = add();
    }
    </script>

    </body>
</html>

I want to ask a question. There is a button on the page that when I click, there is a counter that add 1.

But the add() function make a new var counter = 0; every time I call

And document.getElementById("try").innerHTML = counter; is always 0

The counter now add up 1 --> 2 --> 3 --> 4 ....

I don't understand why it doesn't stay at 1 since the counter is always new and equal to 0 everytime I call the function. Thanks!

user196736
  • 71
  • 7

2 Answers2

0

Calling add() will not execute the var counter = 0; line.

That line only gets executed once according to your code (when declaring the add variable).

You should see this if you test with breakpoints.

Your add function has access to the same counter variable indefinitely since the counter variable was created in the same scope as the add function was defined (function () {return counter += 1;}).

Anthony McGrath
  • 792
  • 5
  • 7
  • Why not? but var counter = 0; is inside the add() function When did the var counter = 0; execute then? Thanks! – user196736 Oct 04 '17 at 04:30
  • The var counter = 0 line is actually in the anonymous function that contains the add function definition. The counter variable is declared once when executing the var add = (function () { line – Anthony McGrath Oct 04 '17 at 05:09
0

It's because you are using an IIFE. So your add variable is what you are returning from the IIFE. So, now your var add becomes

var add = function () {return counter += 1;}

Where counter retains it's previous value because of closure.

And thus on your first click counter is 1, then 2, then 3 and so on.

vs1682
  • 545
  • 2
  • 12