Yesterday I wrote a code wherein, on clicking a button in a page a variable needed to be incremented.
The following function 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 closures 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 be used:
function foo() {
if (! foo.bar) {
foo.bar = 0;
}
return foo.bar++;
}
But the function using closure is the most efficient. In the above, every time foo is invoked, if condition check has to be executed. In the function using closure there is no condition check overhead.