Yesterday, I wrote a piece of code wherein, on clicking a button, a variable had to be incremented.

The following does this:

var bar = 0;
function foo() {
  return bar++;
}

Variable bar will be incremented each time function foo is called.But, what if we don’t want to use global variables? JavaScript closure to the rescue.

var foo = (function () {
   var bar = 0;
   return function() {
     return bar++;
   }
})();

Functionality of the above is the same as that of the first function but, here variable bar is no longer a global variable.

If you are allergic to closures, below function can also be used to eliminate the global variable.

function foo() {
  if  (! foo.bar)  {
    foo.bar = 0;
  }
  return foo.bar++;
}
Advertisements