You can use .valueOf to do the trick:
function myfunction(sum){ var accum = function(val) { sum += val; return accum; }; accum.valueOf = function() { return sum; }; return accum(0); }; var total = myfunction(1)(2)(3)(4); console.log(total);
JSFiddle: http://jsfiddle.net/vdkwhxrL/
How it works:
at each iteration, you return a link to the battery function. But when you request the result, .valueOf() is called, which returns a scalar value.
Note that the result is still a function. Most importantly, this means that it is not copied when assigned:
var copy = total var trueCopy = +total // explicit conversion to number console.log(copy) // 10 ; so far so good console.log(typeof copy) // function console.log(trueCopy) // 10 console.log(typeof trueCopy) // number console.log(total(5)) // 15 console.log(copy) // 15 too! console.log(trueCopy) // 10
source share