How to find loan term given monthly interest rate, monthly payment and principal

35 Views Asked by At

Here's my JS function to calculate loan term which works, however when I put a value for the interestRate higher than 6, it creates an infinite loop. Please help

export const calculateLoanTerm = (amount, interestRate, monthlyPayment) => {
  
  const monthlyInterestRate = interestRate / 100;
  let balance = amount;
  let term = 0;

  while (balance > 0) {
    const interest = balance * monthlyInterestRate;
    const payment = Math.min(monthlyPayment, balance + interest);
    balance -= payment - interest;
    term++;

    if (balance <= 0) break;
  }
  return term;
};

How can I restructure and avoid the loop?

Use test values;

interestRate = 7 // If you use 6 it works
monthlyPayment = 4,500,000
amount = 65,000,000
0

There are 0 best solutions below