Javascript Mortgage Math

I’m constantly assessing various financial situations and the like, either to validate a hypothesis or just to evaluate my own spending. One thing that annoys the crap out of me is the mortgage repayment calculators available on the first page of Google.

All of them are biased or opinionated.

The math is actually somewhat simple and I remember learning it in Year 10. Unfortunately, I don’t really remember that far back so I’ve had to look it up.

Calculate Total Repaid

This is fairly simple because we have a very simple formula.

A = Amount
P = Principal
r = interest Rate, as decimal
n = Number of times interest is calculated 
t = Time in years

A = P(1+r/n)^(nt)

Converting this into Javascript is quite easy, although not super straight forward:

var p = this.#principal
var r = this.#rate / 100
var n = this.determineN()
var t = this.#term
var repayment = (p * ( r / n )) / (( 1 - ( 1 + ( r / n ) ) ** (n * t * -1)) )
return Math.round(repayment)              // Round up to nearest int
var A
var P = 500000
var r = 0.08
var n = 12
var t = 30

var A = P*(1+r/n)**(nt)