2

I wanted to try out recursion to calculate compounding interest rather than a loop.

In Ruby:

def compound balance, percentage
  balance + percentage / 100 * balance
end

def invest amount, years, rate
  return amount if years == 0
  invest compound(amount, rate), years - 1, rate
end

This works fine. $10,000 after 1 year at 5% is $10,500; after 10 years, $16,288.

Now the same logic in JavaScript (ES6).

function compound(balance, percentage) {
    return balance + percentage / 100 * balance;
}

function invest(amount, years, rate) {
    if (years === 0) {
        return amount;
    } else {
        invest(compound(amount, 5), years - 1, rate);
    }
}

This returns undefined, but I can't figure out why. It's calling invest the correct number of times, with the correct parameters, and the logic is the same. The compound function works, I tested that separately. So... what could be wrong?

1 Answer 1

5

Ruby functions automatically return the last expression's value if the step-by-step code "falls off" the end of the function. JavaScript (and most other programming languages) don't do that, so you need to return the value in the else clause explicitly:

function invest(amount, years, rate) {
    if (years === 0) {
        return amount;
    } else {
       return invest(compound(amount, 5), years - 1, rate);
    }
}

Or using the conditional operator:

function invest(amount, years, rate) {
    return years === 0 ? amount : invest(compound(amount, 5), years - 1, rate);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh, that solves it. Thank you for this. I did know JS lacked implicit returns, but I assumed the eventual return amount would return from the entire series of recursive calls. I guess it just returns to the stack frame that called it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.