I am trying to write a basic amortization calculator program in JavaScript and I am at a standstill. I have researched my issue online for hours without being able to come up with a resolution. In my program I have created a "for" loop which loops for the appropriate loan term, however, none of my other calculations change in the loop. They all remain identical to the first row (except for the number of months). Below is the code that I have thus far. I am not looking for anyone to provide the actual correct code, but simply ideas regarding why my loop does not work properly or a direction to head into. I have found tons of slightly different javascript codes regarding amortizations schedules, but I don't want to use those and I would like to learn how to get my own code to work. Any help would be appreciated.

function amort(balance, interestRate, numMonths)
{
	var monthlyRate = interestRate / 12;
	var payment = balance * (monthlyRate / (1 - Math.pow(1 + monthlyRate, -terms)));
	
	var result = "Loan amount: $" + balance.toFixed(2) + "<br />" + 
	"Interest rate: " + (interestRate * 100).toFixed(2) + "%<br />" +
	"Number of months: " + terms + "<br />" +
	"Monthly payment: $" + payment.toFixed(2) + "<br />" +
	"Total paid: $" + (payment * terms).toFixed(2) + "<br /><br />";
	
	result += "<table border='1'><tr><th>Month</th><th>Balance</th>" + //creates table headers
			"<th>Interest</th><th>Principal</th>";

			
	var interestPaid = balance * monthlyRate; //calculates the interest paid each month
	var principalPaid = payment - interestPaid; //calculates the principal paid each month
	var newBalance = balance - principalPaid; // calculates a new monthly balance 
						
		for (var i = 1; i <= numMonths; i++ ){  //starts loop and increments number of months by one up to the inputted loan term
		result += "<tr><td>" + i + "</td><td>" + balance.toFixed(2) + "</td><td>" + interestPaid.toFixed(2) + "</td>" + "<td>" + principalPaid.toFixed(2) + "</td></tr>"
				
									
				}
				
				
		result += "</table>"; 
		return result
			
}

After quite a bit more trial and error and rewriting the code all over again a few times I was finally able to get my code to work properly. The problem seems to have been in my variables and math and reworking it from scratch seemed to give me a better perspective on the problem(s).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.