Javascript - Using closures to implement a magic counter

22 November 2020, 12:51 pm by antelove19


Oreilly Head First JavaScript Programming 1

Using closures to implement a magic counter

Ever think of implementing a counter function? It usually goes like this:

var count = 0; // We have a global variable count.

// Each time we call counter, we increment the global count variable, and return the new value.
function counter() {
    count = count + 1;
    return count;

And we can use our counter like this:

// So we can count and display the value of the counter like this.
console.log( counter() ); // 1
console.log( counter() ); // 2
console.log( counter() ); // 3

The only issue with this is that we have to use a global variable for count, which can be problematic if you’re developing code with a team (because people often use the same names, which end up clashing).

What if we were to tell you there is a way to implement a counter with a totally local and protected count variable? That way, you’ll have a counter that no other code can ever clash with, and the only way to increment the counter value is through the function (otherwise known as a closure).

To implement this with a closure, we can reuse most of the code above. Watch and be amazed:

function makeCounter() {

    // Here, we’re putting the count variable in the function makeCounter. So now count is a local variable, not a global variable.
    var count = 0;

    // Now, we create the counter function, which increments the count variable
    function counter() {
        count = count + 1;

        return count;

    // This is the closure. It holds count in its environment
    return counter; // And return the counter function.


var doCount = makeCounter();

console.log( doCount() ); // 1
console.log( doCount() ); // 2
console.log( doCount() ); // 3

  1. Oreilly, "Oreilly Head First JavaScript Programming", page 498 

Video not yet
0 comment