Reputation: 2608
I have a code
var variable = 0;
function add() {
return variable += 1;
}
console.log(add());
console.log(add());
Im wonder is there a way to write this code only using function and scope, smth like
function add() {
/* SET INITIAL STATE IF NOT SET*/
/* EXECUTE */
/* RETURN NEW VAL */
}
add(); /* RETURN 1*/
add(); /* RETURN 2*/
to get the same result.
Thank you.
Upvotes: 0
Views: 64
Reputation: 716
Also could see the yield operator (generator functions), or console.count()
var add = function () {
var generate = function *inc() {
var i = 0
do {
i++
yield i
} while(true)
}()
return function() {
return generate.next().value
}
}()
console.log(add())
console.log(add())
console.log(add())
Upvotes: 0
Reputation: 1074276
...only using one function...
Your code does use only one function (add
). If you mean you don't want it to close over variable
, you can store the count elsewhere, for instance as a property on the function itself:
function add() {
if (!add.variable) {
add.variable = 0;
}
return ++add.variable;
}
console.log(add());
console.log(add());
console.log(add());
But of course, that means any code can access and change it.
The usual thing is to close over the variable, and perhaps hide it in a scope where nothing else can see it:
var add = (function() {
var variable = 0;
return function add() {
return ++variable;
};
})();
console.log(add());
console.log(add());
console.log(add());
Upvotes: 5
Reputation: 122906
You can create a pseudo static variable for the function:
(() => {
document.querySelector("#test").addEventListener("click", () => console.log(add(1)));
function add(n) {
add.constant = add.constant || 0;
add.constant += n;
return add.constant;
}
})()
<button id="test">add 1</button>
Upvotes: 1