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());

You need to declare n outside of the function.

var n = 0;

function increment(){

  n++;
  return n;
}

The problem is scopes. when you declare a variable inside of a function it is bound to the local scope of the function. as soon as the function is done the variable is gone.

declaring the variable in the root level of the script places it in the global scope.

another way to do this would be to have a variable outside that you're passing around and then you pass it to the function via a parameter.

var i = 0;

function increment(n){

  n++;
  return n;
}

i=increment(i);

for more information on scopes and variables, review this page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Variable_scope

Tags:

Javascript