DEV Community

Tanzeel abbas
Tanzeel abbas

Posted on

Mortgage Amortization Math, Explained with Code

Mortgage Amortization Math, Explained with Code

Every mortgage calculator hides the same elegant math: the amortization formula. Here's the full breakdown with JavaScript.

Skip the math with the free Mortgage Calculator — monthly payment, total interest, and payoff scenarios.

The core formula

function monthlyPayment(principal, annualRate, years) {
  const r = annualRate / 12;
  const n = years * 12;
  if (r === 0) return principal / n;
  const factor = Math.pow(1 + r, n);
  return principal * (r * factor) / (factor - 1);
}
// $400,000 loan, 6.5% APR, 30 years → $2,528.27/mo
Enter fullscreen mode Exit fullscreen mode

Amortization schedule

function amortizationSchedule(principal, annualRate, years) {
  const r = annualRate / 12;
  const payment = monthlyPayment(principal, annualRate, years);
  let balance = principal;
  const schedule = [];
  for (let month = 1; month <= years * 12; month++) {
    const interest = balance * r;
    const principalPaid = payment - interest;
    balance -= principalPaid;
    schedule.push({ month, interest: +interest.toFixed(2), principal: +principalPaid.toFixed(2), balance: +Math.max(balance, 0).toFixed(2) });
    if (balance <= 0) break;
  }
  return schedule;
}
Enter fullscreen mode Exit fullscreen mode

Extra payments

function payoffWithExtra(principal, annualRate, years, extraMonthly) {
  const r = annualRate / 12;
  const basePayment = monthlyPayment(principal, annualRate, years);
  let balance = principal, months = 0, totalInterest = 0;
  while (balance > 0) {
    const interest = balance * r;
    totalInterest += interest;
    balance -= (basePayment + extraMonthly - interest);
    months++;
  }
  return { years: (months / 12).toFixed(1), totalInterest: +totalInterest.toFixed(2) };
}
Enter fullscreen mode Exit fullscreen mode

Calculate yours

The Mortgage Calculator runs all of this instantly — free, no signup, computed locally in your browser.

Top comments (0)