Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment value each time when you run function

Tags:

javascript

So I need a function which increments the value of a variable say n=0. When ever the function runs, the value of this varible must be incremented and it should not be equal to 0 again. For example consider the following code :

function increment(){
  var n = 0;
  n++;
  return n;
}

Now everytime you run this function you get a value of 1. But my requirement is if you run this function for the 1st time, it should be 1, if you run it for the second time, it should be 2 and so on. Unless you refresh the html page and run the function again, it should not be equal to 0. Can anybody help me?

I'm new to coding and any small help is appreciated. Thanks in advance!!!

like image 203
Gopal1216 Avatar asked Feb 17 '14 21:02

Gopal1216


People also ask

How do you increment a variable every time script is running in Python?

To increment a variable in Python use the syntax += 1 , for example to increment the variable i by 1 write i += 1 .

Can you increment a function?

Increment() Function It takes a variable and increments (changes) its value, and also returns this value. The increment can be a positive or negative number. Note: The Increment() function changes the value of its first argument.

Can you do ++ in JavaScript?

JavaScript has an even more succinct syntax to increment a number by 1. The increment operator ( ++ ) increments its operand by 1 ; that is, it adds 1 to the existing value. There's a corresponding decrement operator ( -- ) that decrements a variable's value by 1 .


1 Answers

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());
like image 115
Xotic750 Avatar answered Sep 22 '22 23:09

Xotic750