DEV Community

jiaming
jiaming

Posted on

How to Build a Compound Interest Calculator with Vanilla JavaScript

Compound interest is one of the most powerful concepts in personal finance. I built a tool to visualize it, and in this post I'll walk through the math and code.

The Math

The compound interest formula:

A = P * (1 + r/n)^(n*t)
Enter fullscreen mode Exit fullscreen mode

Where:

  • A = final amount
  • P = principal (initial investment)
  • r = annual interest rate (decimal)
  • n = compounding frequency per year
  • t = time in years

The JavaScript Implementation

function compoundInterest(principal, rate, frequency, years) {
  const r = rate / 100;
  const amount = principal * Math.pow(1 + r / frequency, frequency * years);
  return {
    totalAmount: amount.toFixed(2),
    totalInterest: (amount - principal).toFixed(2),
    yearlyBreakdown: generateBreakdown(principal, r, frequency, years)
  };
}

function generateBreakdown(principal, rate, frequency, years) {
  const breakdown = [];
  let balance = principal;
  for (let year = 1; year <= years; year++) {
    balance = principal * Math.pow(1 + rate / frequency, frequency * year);
    breakdown.push({
      year,
      balance: balance.toFixed(2),
      interest: (balance - principal).toFixed(2)
    });
  }
  return breakdown;
}
Enter fullscreen mode Exit fullscreen mode

Why Compounding Frequency Matters

The difference between daily and annual compounding isn't trivial. On a $10,000 investment at 7% over 30 years:

  • Annually: $76,122
  • Monthly: $80,729
  • Daily: $81,660

That's a $5,538 difference just from compounding frequency.

The Power of Starting Early

Here's where it gets interesting. Two investors:

  • Alice starts at 25, invests $200/month for 10 years, then stops
  • Bob starts at 35, invests $200/month for 30 years

At 65, assuming 7% returns: Alice ends up with more money than Bob despite investing for 20 fewer years. That's compound growth doing the heavy lifting.

If you want to run your own numbers, I built a free calculator that handles dual-frequency compounding, monthly contributions, and visualizes the growth curve: https://finikit.com/tools/compound-calculator.html

The full source for this calculator is available on the site. Happy to answer questions about the implementation below.

Top comments (0)