Usually, for creating counter we create a global variable.
var counter = 0;
function addInCounter(){
counter +=1;
}
This is not good practice to do that because counter variable exposed to global scope in this. We can use closure to do that.
Full Example
var counter = 0;
function addInCounter(){
counter +=1;
}
This is not good practice to do that because counter variable exposed to global scope in this. We can use closure to do that.
Full Example
<!DOCTYPE html> <html> <body> <p>Counting with a local variable.</p> <button type="button" onclick="addInCounter()">Count!</button> <p id="demo">0</p> <script> var add = (function () { var counter = 0; return function () {return counter += 1;} })(); function addInCounter(){ document.getElementById("demo").innerHTML = add(); } </script> </body> </html>