When I call a function using a method, it’s returns undefined and Nan.
When it’s called counter.increment, it should return the input "init" + 1, counter.decrement should return "init" – 1 and counter.reset should return the initial value of "init". But instead for some reason, the three console.log returns undefined and the function createCounter returns NaN.
var createCounter = function(init) {
return {
increment: (init) => {
console.log(init);
return init++;
},
decrement: (init) => {
console.log(init);
return init--;
},
reset: (init) => {
console.log(init);
return init;
}
}
};
const counter = createCounter(5)
counter.increment(); // 6
counter.reset(); // 5
counter.decrement(); // 4
3
Answers
Remove
init
from all the function calls so they correctly use the outerinit
closed over in scope from thecreateCounter
call. You are trying to update an undefined localinit
value which results inNaN
.Save the initial
init
into a local variable that can be mutated.Note also the console logs are logging the starting value, not the resulting value. It’s trivial to capture the result first for logging before returning it.
Note also that your logic uses postfix
++
/--
operators, meaning that the value is returned and then the value is incremented/decremented.If you desire for the returned value to be the updated value then use the prefix
++
/--
operators instead, which increments/decrements first and returns the updated value. Just move the operator in front of the variable you are incrementing/decrementing.Suggested edit:
EDIT: This answer merely illustrates the problem; for the solution, see @Drew Reese’s answer.
Your outer
init
is not being used, since its being shadowed by theinit
passed as argument to the inner functions. So to use your code as it is now, you would need to do the following:[Please don’t do this, it defeats the whole purpose of a counter]
Notice the change of
init++
to++init
(and similarly with--init
).Of course, the above code isn’t very useful, so to do what you really want to do, remove the
init
argument of the inner functions, as @Drew Reese shows in their answer.