Home loan calculators look simple from the outside: type in a loan amount, a rate and a term, and a repayment figure appears. Under the hood, most of them run the same standard amortisation formula. If you are building one for a personal finance project, here is how it works in plain JavaScript.
The repayment formula
For a principal and interest loan, the regular repayment is:
M = P * r * (1 + r)^n / ((1 + r)^n - 1)
-
Pis the loan amount -
ris the interest rate per period (annual rate divided by the number of payments per year) -
nis the total number of payments
A small JavaScript function
function repayment(principal, annualRatePct, years, periodsPerYear = 12) {
const r = annualRatePct / 100 / periodsPerYear;
const n = years * periodsPerYear;
if (r === 0) return principal / n;
const factor = Math.pow(1 + r, n);
return principal * r * factor / (factor - 1);
}
// Example: $600,000 over 30 years at 6% p.a., paid monthly
console.log(repayment(600000, 6, 30).toFixed(2)); // 3597.30
Switching periodsPerYear to 26 gives a fortnightly figure, which is how many Australian borrowers choose to repay.
Interest only repayments
Interest only loans are even simpler, because the balance does not reduce during the interest only period:
function interestOnly(principal, annualRatePct, periodsPerYear = 12) {
return principal * (annualRatePct / 100) / periodsPerYear;
}
Things a real calculator should consider
A basic formula is a good start, but production calculators usually add:
- Fees and charges that change the true cost of the loan
- Offset accounts and extra repayments that shorten the term
- Rate changes over the life of the loan
- Borrowing power, which depends on income, expenses and each lender's own assessment rules
That last point is where simple calculators fall short. Lenders apply different buffers and expense assumptions, so the same borrower can get quite different results from different banks.
See it in practice
If you want to compare your own numbers against working tools, The Finance Yogi, a Perth mortgage broker, publishes a set of home loan calculators covering repayments and related scenarios. They are a useful reference when you are checking that your own implementation returns sensible figures.
Building your own version is a great way to understand what actually drives a repayment, and to see why comparing lenders matters as much as the headline rate.
Top comments (0)