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
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:
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: