Inspired by If Hemingway Wrote Javascript, I'm trying to write a chainable function closure with a private local variable.
The intended behavior is:
> chainableCounter()
0
> chainableCounter(1)(2)()
3
Here's my code:
function chainableCounter(n) {
var acc = 0;
var fn = function (x) {
if (x === undefined) {
return acc;
} else {
acc = acc + x;
return fn;
}
};
fn(n);
}
When I try to run this in the node REPL, this is what I get:
> chainableCounter()
undefined
> chainableCounter(1)
undefined
> chainableCounter(1)()
TypeError: undefined is not a function
That chainableCounter(1)
returns undefined
instead of a function object seems to indicates that we're never hitting the line return fn;
. But more than that, why does chainableCounter()
also returning undefined
when it should return 0
? What am I missing?
fn(n)
returns to the point of the call. Your actual function chainableCounter
doesn't return anything, it doesn't have a return statement.
You can just add it before calling fn
, like this:
return fn(n);