Increment value each time when you run function

Create a closure to hold the value

Closures are functions that refer to independent (free) variables.

In short, variables from the parent function of the closure remain bound from the parent’s scope.

var increment = (function(n) {
  return function() {
    n += 1;
    return n;
  }
}(0)); // -1 if you want the first increment to return 0

console.log(increment());
console.log(increment());
console.log(increment());

Leave a Comment