In this lesson, you will learn how to add, edit, and delete expenses in our Personal Expense Tracker project. By the end, you will be able to manage your expenses using JavaScript effectively. This skill is essential for keeping track of your spending and budgeting properly.
Imagine you bought a new pair of shoes for $50 last week. Now, you decide to add this purchase to your expense tracker. The process of adding expenses is simple and will set the foundation for your expense management. You will use a function called addExpense for this task. First, you create an expense object with details like the amount and description. Then, you push it to an array of expenses.
Later, you might realize you spent $20 on lunch last Saturday and want to remove it from your records. Editing or deleting expenses requires identifying the right expense using its unique id. You will use the editExpense function for updates and the deleteExpense function to remove items. Understanding how to manage these records is crucial because your financial situation can change rapidly. Therefore, learning to add, edit, and delete expenses is vital.
File: expenseTracker.js
const expenses = [];
function addExpense(name, amount) {
const expense = { id: Date.now(), name, amount };
expenses.push(expense);
}
function editExpense(id, newName, newAmount) {
const expense = expenses.find(exp => exp.id === id);
if (expense) {
expense.name = newName;
expense.amount = newAmount;
}
}
function deleteExpense(id) {
const index = expenses.findIndex(exp => exp.id === id);
if (index !== -1) {
expenses.splice(index, 1);
}
}
The function addExpense creates an expense object and adds it to the expenses array. Also, the editExpense function updates an existing expense using its unique id. The deleteExpense function removes an expense from the array by finding its index and using splice. In addition, you can create a function to view all expenses. This way, you can always understand where your money is going.
Now it’s your turn! Create a new function called viewExpenses. This function should log all expenses to the console. Use the following structure:
function viewExpenses() {
console.log(expenses);
}
function viewExpenses() {
console.log(expenses);
}
id based on Date.now(). This practice helps you accurately track your expenses.To enhance your understanding of coding concepts, refer to the lesson on What Is JavaScript? where you can find examples from everyday websites. Also, incorporating coding best practices is vital for building reliable applications.