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:
- About this project
- Alternative to declaring const for each variable
- Alternative to addEventListener of submit
- Alternative to if else – Conditional (ternary) operator
- Create a function that gets values from HTML input tags
- 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) + "$");
}