Jeremy Iglehart Jeremy Iglehart - 1 year ago 68
Javascript Question

addNumbers(1)(2)(3)... How to call a function arbitrary number of times and have it add up?

Consider the following example:

function thisNumberWrapper(wrapperNumber) {
function multiply(anotherNumber) {
console.log(`This is your number: ${wrapperNumber} times another number: ${anotherNumber}: ${wrapperNumber * anotherNumber}`)
return multiply

let wrappedNumber = thisNumberWrapper(2)(4)

This works just fine... But what I would like to do is have a function that works like so:

and get back

Is this possible?

Obviously I've googled around and looked for this here on stackoverflow - but I can't find anything anywhere that has this pattern. I was working on a project a long time ago and we were using this type of "recursion" for a specific use case - I was looking to do that again.

Does anyone know how to pattern this out?

Edit: Getting closer

function addNumbers(number) {
return addNumbers


But it's still not working.

Answer Source

implement valueOf & toString of Embedded Function

function multiply(x) {
    var result = x;  

    function f(y) { 
        result *= y;
        return f;
    f.toString = function () { return result; }; // for expecting string, 1st log
    f.valueOf = function () { return result; };  // for expecting number, 2nd log

    return f;



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download