Hey there! I wanted to talk about a piece of code I wrote for a school project! It’s a program that calculates the amount of tax owed based on a given income and a set of tax brackets. It’s a relatively simple implementation that should be easy to follow, even if you’re new to programming.
Here’s an overview of how the Javascript code works, with some code snippets and explanations to make things clearer:
Step 1: Initialize Event Listeners
The first step is to initialize event listeners for the two buttons on the page: one for processing the salary input and one for clearing the results. Here’s the code for that:
const init = () => {
let salaryButton = document.querySelector("#salary-button");
salaryButton.addEventListener("click", processSalary);
let clearButton = document.querySelector("#clear-button");
clearButton.addEventListener("click", clearResults);
};
The init
function sets up event listeners for the #salary-button
and #clear-button
elements. When the #salary-button
is clicked, it calls the processSalary
function, which we’ll look at next. When the #clear-button
is clicked, it calls the clearResults
function, which clears the results box on the page.
Step 2: Process Salary Input
The processSalary
function is called when the #salary-button
is clicked. It retrieves the gross salary input from the page and calculates the federal, state, medicare, and social security taxes owed based on the gross salary and a set of tax brackets.
1. Retrieve Gross Salary Input
const processSalary = (event) => {
event.preventDefault();
let grossSalaryInput = document.querySelector("#gross-salary");
let grossSalary = grossSalaryInput.value;
// Print gross salary
printResults(grossSalary, "Gross Salary");
// ...
};
The processSalary
function first retrieves the gross salary input from the page using the document.querySelector
method, and stores it in the grossSalaryInput
variable. It then retrieves the value of the input using the .value
property, and stores it in the grossSalary
variable. Finally, it prints the gross salary to the results box using the printResults
function.
2. Calculate Federal Taxes
const processSalary = (event) => {
event.preventDefault();
// ...
// Federal tax brackets
let fedBrackets = [
{ limit: 9875, rate: 10 },
{ limit: 40125, rate: 12 },
{ limit: 85525, rate: 22 },
{ limit: 163300, rate: 24 },
{ limit: 207350, rate: 32 },
{ limit: 518400, rate: 35 },
{ limit: Infinity, rate: 37 }
];
// Calculate federal tax
let fedTaxResults = calcTax(grossSalary, fedBrackets);
// Print federal tax
printResults(fedTaxResults, "Federal Tax");
// ...
};
The processSalary
function initializes the fedBrackets
array with the federal tax brackets, and calculates the federal tax owed using the calcTax
function. It then prints the federal tax results to the results box using the printResults
function.
3. Calculate Other Taxes
const processSalary = (event) => {
event.preventDefault();
// ...
// State tax brackets
let stateBrackets = [
{ limit: 11970, rate: 3.54 },
{ limit: 23930, rate: 4.65 },
{ limit: 263480, rate: 6.27 },
{ limit: Infinity, rate: 7.65 }
];
// Calculate state tax
let stateTaxResults = calcTax(grossSalary, stateBrackets);
// Medicare tax brackets
let medicareBrackets = [
{ limit: 200000, rate: 1.45 },
{ limit: Infinity, rate: 2.35 },
];
// Calculate medicare tax
let medicareTaxResults = calcTax(grossSalary, medicareBrackets);
// Social security tax brackets
let socialBrackets = [
{ limit: 137700, rate: 6.2 },
{ limit: Infinity, rate: 0 },
];
// Calculate social security tax
let socialTaxResults = calcTax(grossSalary, socialBrackets);
// ...
};
The processSalary
function initializes the stateBrackets
, medicareBrackets
, and socialBrackets
arrays with the state, medicare, and social security.
4. Calculate Total Tax and Net Pay
const processSalary = (event) => {
event.preventDefault();
// ...
// Calculate total tax and net pay
let totalTaxes = fedTaxResults + stateTaxResults + medicareTaxResults + socialTaxResults;
let income = grossSalary - totalTaxes;
// Print tax and income results
printResults(fedTaxResults, "Federal Tax");
printResults(stateTaxResults, "State Tax");
printResults(medicareTaxResults, "Medicare Tax");
printResults(socialTaxResults, "Social Security Tax");
printResults(totalTaxes, "Total Taxes");
printResults(income, "Net Pay");
// Clear input field
grossSalaryInput.value = "";
};
The processSalary
function calculates the total taxes owed by adding up the federal, state, medicare, and social security taxes. It then calculates the net pay by subtracting the total taxes from the gross salary. Finally, it prints the tax and income results to the results box using the printResults
function.
Step 3: Calculate Tax Owed
The calcTax
function is the heart of the tax calculator. It takes in an income and a set of tax brackets, and calculates the total amount of tax owed. Here’s the code for that:
const calcTax = (income, brackets) => {
let tax = 0;
let previousLimit = 0;
for (let i = 0; i < brackets.length; i++) {
let bracket = brackets[i];
if (income >= bracket.limit) {
let taxableIncome = bracket.limit - previousLimit;
let taxForBracket = (bracket.rate / 100) * taxableIncome;
tax += taxForBracket;
previousLimit = bracket.limit;
} else {
let remainingIncome = income - previousLimit;
let taxForBracket = (bracket.rate / 100) * remainingIncome;
tax += taxForBracket;
break;
}
}
return tax;
};
The calcTax
function initializes the tax variable to 0 and sets the previousLimit variable to 0. It then loops through each bracket in the brackets array and checks if the income is greater than or equal to the bracket’s limit. If the income is greater than or equal to the bracket’s limit, the function calculates the taxable income for that bracket by subtracting the previous limit from the current limit. It then calculates the tax owed for that bracket by multiplying the taxable income by the bracket’s tax rate (expressed as a decimal). If the income is less than the bracket’s limit, the function calculates the tax owed for the remaining income by subtracting the previous limit from the income and multiplying it by the bracket’s tax rate. The function adds the tax owed for each bracket to the tax variable and returns the total tax owed.
Step 4: Print Results
const printResults = (result, label) => {
let taxResultsDiv = document.createElement("div");
taxResultsDiv.setAttribute("class", "tax-results-div");
taxResultsDiv.setAttribute("id", label);
taxResultsDiv.innerText = label + ": " + Number(result).toFixed(2);
theResultsBox.appendChild(taxResultsDiv);
};
The printResults
function takes in a result and a label, and prints them to the results box. It first creates a new div
element using the document.createElement
method, and sets the class and ID attributes using the setAttribute
method. It then sets the inner text of the div
element using the innerText
property, and appends the div
element to the results box using the appendChild
method.
Here is the entire javascript code altogether with minor differences –
let theResultsBox;
const init = () => {
let salaryButton = document.querySelector("#salary-button");
salaryButton.addEventListener("click", processSalary);
let clearButton = document.querySelector("#clear-button");
clearButton.addEventListener("click", clearResults);
theResultsBox = document.querySelector("#results-box");
};
const processSalary = (event) => {
event.preventDefault();
let grossSalaryInput = document.querySelector("#gross-salary");
let grossSalary = grossSalaryInput.value;
printResults(grossSalary, "Gross Salary");
let fedBrackets = [
{ limit: 9875, rate: 10 },
{ limit: 40125, rate: 12 },
{ limit: 85525, rate: 22 },
{ limit: 163300, rate: 24 },
{ limit: 207350, rate: 32 },
{ limit: 518400, rate: 35 },
{ limit: Infinity, rate: 37 }
];
let fedTaxResults = calcTax(grossSalary, fedBrackets);
let stateBrackets = [
{ limit: 11970, rate: 3.54 },
{ limit: 23930, rate: 4.65 },
{ limit: 263480, rate: 6.27 },
{ limit: Infinity, rate: 7.65 }
];
let stateTaxResults = calcTax(grossSalary, stateBrackets);
let medicareBrackets = [
{ limit: 200000, rate: 1.45 },
{ limit: Infinity, rate: 2.35 },
];
let medicareTaxResults = calcTax(grossSalary, medicareBrackets);
let socialBrackets = [
{ limit: 137700, rate: 6.2 },
{ limit: Infinity, rate: 0 },
];
let socialTaxResults = calcTax(grossSalary, socialBrackets);
let totalTaxes = fedTaxResults + stateTaxResults + medicareTaxResults + socialTaxResults;
let income = grossSalary - totalTaxes;
printResults(fedTaxResults, "Federal Tax");
printResults(stateTaxResults, "State Tax");
printResults(medicareTaxResults, "Medicare Tax");
printResults(socialTaxResults, "Social Security Tax");
printResults(totalTaxes, "Total Taxes");
printResults(income, "Net Pay");
grossSalaryInput.value = "";
};
const printResults = (result, label) => {
let taxResultsDiv = document.createElement("div");
taxResultsDiv.setAttribute("class", "tax-results-div");
taxResultsDiv.setAttribute("id", label);
taxResultsDiv.innerText = label + ": " + Number(result).toFixed(2);
theResultsBox.appendChild(taxResultsDiv);
};
const clearResults = (event) => {
event.preventDefault();
theResultsBox.innerHTML = "";
};
const calcTax = (income, brackets) => {
let tax = 0;
let previousLimit = 0;
for (let i = 0; i < brackets.length; i++) {
let bracket = brackets[i];
if (income >= bracket.limit) {
taxableIncome = bracket.limit - previousLimit;
let taxForBracket = (bracket.rate / 100) * taxableIncome;
tax += taxForBracket;
previousLimit = bracket.limit;
} else {
let remainingIncome = income - previousLimit;
let taxForBracket = (bracket.rate / 100) * remainingIncome;
tax += taxForBracket;
console.log(bracket.limit + " = limit " + bracket.rate + " = rate " + income + " = income " + tax + " = tax");
break;
}
}
return tax;
};
And that’s it! I hope this post helped you understand how the tax calculator works. If you have any questions or feedback, feel free to leave a comment below.