By the end of this lesson, you will be able to calculate totals, filter records, and save your expense data in JavaScript. This skill is crucial for maintaining personal or business finances effectively.
Calculating totals and filtering records is essential in any expense tracker. For example, you may want to know how much you spent on food last month. Understanding this feature helps you manage your budget better. It also allows you to track your spending habits over time.
File: expenseTracker.js
const expenses = [
{ id: 1, category: 'Food', amount: 50 },
{ id: 2, category: 'Transport', amount: 20 },
{ id: 3, category: 'Food', amount: 30 },
{ id: 4, category: 'Utilities', amount: 100 }
];
function calculateTotal(category) {
let total = 0;
expenses.forEach(expense => {
if (expense.category === category) {
total += expense.amount;
}
});
return total;
}
function filterRecords(category) {
return expenses.filter(expense => expense.category === category);
}
function saveData() {
localStorage.setItem('expenses', JSON.stringify(expenses));
}
// Example usage:
console.log('Total Food Expenses: $', calculateTotal('Food'));
console.log('Filtered Food Records: ', filterRecords('Food'));
saveData();
Total Food Expenses: $ 80
Filtered Food Records: [ { id: 1, category: 'Food', amount: 50 }, { id: 3, category: 'Food', amount: 30 } ]
In this code, we have an array of expense objects. The calculateTotal function sums the amounts of a specific category. This function is called when you want to know the total for a specific type of spending. The filterRecords function returns all expenses of a chosen category. Therefore, you can view exactly how much was spent on that category. Finally, the saveData function saves the expenses in localStorage so you can retrieve it later. In addition, this ensures your data lasts even after refreshing the page.
First, modify the provided code. Add a function that calculates the total amount for all expenses, not just by category. Next, call this function and display the result in the console. Doing this will give you a broader view of your expenses and help you make informed decisions.
function calculateTotalAll() {
return expenses.reduce((sum, expense) => sum + expense.amount, 0);
}
console.log('Total All Expenses: $', calculateTotalAll());
saveData() after updating expenses. This prevents accidental data loss.localStorage for later use; this helps maintain your data.If you wish to explore more about JavaScript fundamentals, check our lesson on What Is JavaScript? This will provide a solid foundation before diving into concepts like calculating totals. Furthermore, understanding how to connect JavaScript with HTML and CSS will enhance your development skills.