Vishnu Paspunoor Vishnu Paspunoor - 6 months ago 8
Javascript Question

Modifying a local variable in Javascript every time the function is called

I want to increment the value of

i
everytime I call
myFunction()
. As you can see, every time the value of
i
gets initialized to
0
. So the result will always be zero. How to ensure that
i
remains a local variable and get the increment?

function myFunction(){
var i = 0;
console.log(i);
i++
};
myFunction();
myFunction();
myFunction();
myFunction(); // Result must be 3

Answer

A little modification on @Carlo's answer. This keeps myFunction in the current scope.

var myFunction = (function() {
  var i = 0;
  return function (){
    console.log(i);
    i++;
  };
})();

Example:

myFunction(); // logs 0
myFunction(); // logs 1
myFunction(); // logs 2
myFunction(); // logs 3
Comments