<!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!