Type Here to Get Search Results !

How to create counter in JavaScript without using Global variable?

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


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


Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Top Post Ad

bogger post ad 1

Below Post Ad

bogger post ad 2

ezoic

Ads Section