The Code for Loan Calculator.


                        
                        // Get values from page
                        function getValues(){
                            let loanAmount = document.getElementById("loanAmountInput").value;
                            let months = document.getElementById("totalMonthsInput").value;
                            let rate = document.getElementById("rateInput").value;

                            if (loanAmount == ""){
                                loanAmount = parseFloat(15000);
                            } else {
                                loanAmount = parseFloat(loanAmount);
                            }

                            if (months == ""){
                                months = parseFloat(60);
                            } else {
                                months = parseFloat(months);
                            }

                            if (rate == ""){
                                rate = parseFloat(3);
                            } else {
                                rate = parseFloat(rate);
                            }
                            
                            // do loan calculations
                            let resultsHTML = loanCalculations(loanAmount, rate, months);

                            // display the html to screen
                            displayResults(resultsHTML);
                        }

                        // Calculations
                        function loanCalculations(loanAmount, rate, months){

                            let resultsObject = {};

                            let totalInterest = 0;
                            let balance = loanAmount;
                            let interestPayment = 0;
                            let principalPayment;
                        
                            // Calculate the total monthly payment
                            let monthExponent = -Math.abs(months);
                            let monthlyPayment = (loanAmount * (rate/1200)) / (1-(1+(rate/1200))**(monthExponent));
                            monthlyPayment = parseFloat(monthlyPayment);
                            
                            let html = "";
                            
                            for (let i = 1; i <= months; i++){
                                let month = i;
                                interestPayment = parseFloat(balance*(rate/1200));
                                principalPayment = parseFloat(monthlyPayment - (balance * (rate/1200)));
                                totalInterest = parseFloat((totalInterest + interestPayment));
                                totalInterest = parseFloat(totalInterest);
                                balance -= principalPayment;
                                balance = Math.abs(parseFloat(balance));

                                html += `${month}${monthlyPayment.toFixed(2)}${principalPayment.toFixed(2)}${interestPayment.toFixed(2)}${totalInterest.toFixed(2)}${balance.toFixed(2)}`
                            }
                            
                            let totalCost = loanAmount + totalInterest;

                            // display calculated variables to proper positions while inside function
                            // use the .toLocaleString to convert to USD format 
                            resultsObject.monthlyPayment = monthlyPayment.toLocaleString('en-US', {
                                style: 'currency',
                                currency: 'USD',
                            });

                            resultsObject.totalPrincipal = loanAmount.toLocaleString('en-US', {
                                style: 'currency',
                                currency: 'USD',
                            });
                            
                            resultsObject.totalInterest = totalInterest.toLocaleString('en-US', {
                            style: 'currency',
                            currency: 'USD',
                            });

                            resultsObject.totalCost = totalCost.toLocaleString('en-US', {
                                style: 'currency',
                                currency: 'USD',
                                });

                            resultsObject.html = html;

                            return resultsObject;
                        }

                        // Display results
                        function displayResults(resultsObject){
                            document.getElementById("monthPaymentsOutput").innerHTML =  resultsObject.monthlyPayment;
                            document.getElementById("totalPrincipalOutput").innerHTML = resultsObject.totalPrincipal;
                            document.getElementById("totalInterestOutput").innerHTML = resultsObject.totalInterest;
                            document.getElementById("totalCostOutput").innerHTML =  resultsObject.totalCost
                            document.getElementById("results").innerHTML = resultsObject.html;
                        }

                        // Reset page
                        function resetPage(){
                            loanAmount = document.getElementById("loanAmountInput").value = "";
                            months = document.getElementById("totalMonthsInput").value = "";
                            rate = document.getElementById("rateInput").value = "";
                            document.getElementById("monthPaymentsOutput").innerHTML = "";
                            document.getElementById("totalPrincipalOutput").innerHTML = "";
                            document.getElementById("totalInterestOutput").innerHTML = "";
                            document.getElementById("totalCostOutput").innerHTML = "";
                            document.getElementById("results").innerHTML = "";
                        }
                    
                    

Here are some brief explanations of the functions used in this project.

getValues()

 This function kicks off the application. We first pull in the values entered into our input fields. I added some if/then/else statements to see if the user entered their own values or if they wanted to just use the placeholder values. If they don't enter anything themselves, then we will just use the placeholders. Next, I pass those three parameters into our loanCalculations( ) function where most of the heavy lifting will occur. Finally, we send the resulting HTML string from there, and pass it into our displayResults( ) function so we can put the rest on the web page.

loanCalculations()

 This is where most of the action occurs. First, we create a resultsObject to store all of our results inside. We will return this later. Next, we set up various variables we will need to generate the table rows and output needed later. Some variables are set to known values, and some are set to 0 since logically this is how they will start. Next, we calculate the monthly payment based on user input, and use the built-in >parseFloat( ) to ensure the variable's value is a float, and not a string. You will see this multiple times later.

 Next, we declare our html variable, and set it to an empty string. We will be adding to this string with every pass through the coming for loop. This is how we build out our table for the results output. Inside the for loop we set i = 1, and make sure it runs once for every month the user selected for the loan term. During each pass through the loop we calculate a changing set of values based on simple formulas, and update the balance and total interest before inserting those calculated values into a string representing a row in an HTML table. You'll notice that we used the built-in .toFixed(2) on the monthly payment to display a rounded value to the user. We are actually maintaining the precision stored in the monthlyPayment variable while displaying the rounded version. Rounding prematurely will break the math of our application. You may also notice we use the Math.abs function on our balance. What this does is transform the number to its absolute value; I use this to ensure the balance displays a positive value when it hits $0.00.

 Next, we calculate the total cost to the user based on the loan terms entered. We then have a section of code that stores some of the variables we have calculated inside our resultsObject. Notice we converted the monetary values to a USD format. Finally, the resultsObject is returned.

displayResults()

 This function is extremely straight forward. We take our values inside the resultsObject, and inject them into the appropriate element to display our results to the user.

resetPage()

  This function resets the page by setting all of the involved elements' inner HTML to an empty string.