Reputation: 5
function setupCounter(val){
console.log(val);
return function counter(){
console.log('counter func ', val);
return val++;
}
}
debugger
let counter1 = setupCounter(0);
console.log(counter1()); //0
console.log(counter1()); //1
Why the first counter1()
does not increment value and returns 0. But the second call increments the value to 1, as expected: here is what I've been debuggin
Upvotes: 0
Views: 634
Reputation: 927
The issue here is the postfix increment operator doesn't return what you expect. Quoting from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment:
If used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing.
If used prefix, with operator before operand (for example, ++x), the increment operator increments and returns the value after incrementing.
Using val++
will actually return the previous value, rather than what it becomes. If you want it to return the new value, you'd use the increment operator as a prefix, like: ++val
.
Because of this common confusion, I prefer to be more verbose and do something like this:
val += 1;
return val;
Upvotes: 4