Refactoring JavaScript – Compound interest calculator web app

Web Development

In this javascript tutorial you will learn how to refactor javascript code to a more simpler and cleaner cod. We will use a previous project for this as a example.

Table of content:

  1. About this project
  2. Alternative to declaring const for each variable
  3. Alternative to addEventListener of submit
  4. Alternative to if else – Conditional (ternary) operator
  5. Create a function that gets values from HTML input tags
  6. Create a function that calculate the compounded interest rate with also a monthly contribution.
// Get all elements from the dom using id

const compoundInterestCalculator = document.getElementById(
    "CompoundInterestCalculator"
  ),
  initialBalance = document.getElementById("InitialBalance"),
  interestRate = document.getElementById("InterestRate"),
  years = document.getElementById("Years"),
  monthlyContribution = document.getElementById("MonthlyContribution"),
  result = document.getElementById("Result");

// Form validation and submission
compoundInterestCalculator.onsubmit = (e) => {
  e.preventDefault();

  getValues();

  value.principleAmount === "" ||
  value.interestRate === "" ||
  value.years === ""
    ? alert("Complete all fields")
    : calculateCompoundInterest();
};

function getValues() {
  return (value = {
    principleAmount: initialBalance.value,
    interestRate: interestRate.value,
    years: years.value,
    monthlyContribution: monthlyContribution.value,
  });
}

// Calculate compound interest

function calculateCompoundInterest() {
  // Add fade effect

  result.classList.add("fade");
  setTimeout(function () {
    result.classList.remove("fade");
  }, 1000);

  value.monthlyContribution === ""
    ? (result.innerHTML =
        (
          value.principleAmount *
          Math.pow(1 + value.interestRate / 100 / 12, 12 * value.years)
        ).toFixed(2) + "$")
    : (result.innerHTML =
        (
          value.principleAmount *
            Math.pow(1 + value.interestRate / 100 / 12, 12 * value.years) +
          value.monthlyContribution *
            ((Math.pow(1 + value.interestRate / 100 / 12, 12 * value.years) -
              1) /
              (value.interestRate / 100 / 12))
        ).toFixed(2) + "$");
}

Video for this tutorial

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.