Diablo3093
Diablo3093

Reputation: 1053

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? How can this be done with the concept of closures?

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

Upvotes: 2

Views: 85

Answers (5)

galkin
galkin

Reputation: 5519

Put the variable in the global scope:

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

Upvotes: 0

A1rPun
A1rPun

Reputation: 16837

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

Upvotes: 4

Mohammad Usman
Mohammad Usman

Reputation: 39322

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

myFunction();
myFunction();
myFunction();
myFunction(); // Result must be 3

Upvotes: 0

James Long
James Long

Reputation: 4736

As others have suggested, taking the variable out of the function's scope is the answer. An alternative is to set the variable as a property of the function.

function myFunction() {

    if (typeof myFunction.i !== "number") {
        myFunction.i = 0;
    }

    console.log(myFunction.i);
    myFunction.i += 1;

}

Upvotes: 0

Carlo
Carlo

Reputation: 2112

Short answer: take the variable out of the scope.

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

myFunction();
myFunction();
myFunction();
myFunction(); 

Using a wider scope function will prevent your variable from going global.

Upvotes: 3

Related Questions