Reading history

JavaScript Project: Build an Expense Tracker

8 min read Updated 4 views

Build an expense tracker in JavaScript with state and render, form validation, event delegation, safe DOM updates and Intl currency formatting.

In this project you will build an expense tracker: a small app that records income and spending, shows the balance, filters the list and deletes entries. It is a practical way to combine what you have learned: arrays of objects and their methods, form handling and validation, event delegation, safe DOM updates and currency formatting with Intl. Most importantly, it follows a simple structure used by real apps: keep the data in one place, and redraw the page from that data whenever it changes.

In this project you will

  • Store app data as an array of objects (the state)
  • Write one render() function that draws the page from the state
  • Validate form input before adding entries
  • Handle many buttons with one delegated listener
  • Format money with Intl.NumberFormat

This project uses array methods, events and Intl formatting.

The Complete App

Try it: add an expense, try submitting an empty form, switch the filters and delete an entry.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Expense Tracker</title>
  <style>
    * { box-sizing: border-box; }
    body { font-family: system-ui, sans-serif; margin: 0; padding: 14px; background: #f5f7fb; color: #263238; }
    .app { max-width: 560px; margin: 0 auto; }
    h1 { font-size: 22px; margin: 0 0 10px; }
    .summary { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin-bottom: 12px; }
    .stat { background: white; border-radius: 8px; padding: 8px; text-align: center; }
    .stat b { display: block; font-size: 17px; }
    .income b { color: #2e7d32; } .expense b { color: #c62828; }
    form { display: grid; grid-template-columns: 2fr 1fr 1fr auto; gap: 6px; margin-bottom: 10px; }
    input, select, button { font: inherit; padding: 7px; border: 1px solid #b0bec5; border-radius: 6px; min-width: 0; }
    button { background: #3949ab; color: white; border: 0; cursor: pointer; }
    .filters { display: flex; gap: 6px; margin-bottom: 8px; }
    .filters button { background: white; color: #3949ab; border: 1px solid #3949ab; padding: 4px 10px; }
    .filters button.active { background: #3949ab; color: white; }
    ul { list-style: none; padding: 0; margin: 0; }
    li { display: flex; align-items: center; gap: 8px; background: white; padding: 8px 10px; border-radius: 6px; margin-bottom: 6px;
         border-left: 4px solid #c62828; }
    li.in { border-left-color: #2e7d32; }
    li span { flex: 1; }
    li .amt { font-weight: 700; }
    li .del { background: none; color: #90a4ae; padding: 0 4px; font-size: 18px; }
    @media (max-width: 480px) { form { grid-template-columns: 1fr 1fr; } }
    .error { color: #c62828; min-height: 1.2em; margin: 0 0 6px; font-size: 13px; }
  </style>
</head>
<body>
  <div class="app">
    <h1>Expense Tracker</h1>
    <div class="summary">
      <div class="stat"><small>Balance</small><b id="balance"></b></div>
      <div class="stat income"><small>Income</small><b id="income"></b></div>
      <div class="stat expense"><small>Expenses</small><b id="expense"></b></div>
    </div>

    <form id="form">
      <input id="desc" placeholder="Description" aria-label="Description">
      <input id="amount" type="number" step="0.01" placeholder="Amount" aria-label="Amount">
      <select id="type" aria-label="Type"><option value="out">Expense</option><option value="in">Income</option></select>
      <button>Add</button>
    </form>
    <p class="error" id="error" role="alert"></p>

    <div class="filters" id="filters">
      <button data-filter="all" class="active">All</button>
      <button data-filter="in">Income</button>
      <button data-filter="out">Expenses</button>
    </div>
    <ul id="list"></ul>
  </div>

  <script>
    // ---- State: the single source of truth ----
    let items = [
      { id: 1, desc: "Tuition salary", amount: 8000, type: "in" },
      { id: 2, desc: "Books", amount: 650, type: "out" },
      { id: 3, desc: "Bus fare", amount: 120.5, type: "out" },
    ];
    let filter = "all";
    let nextId = 4;

    const money = new Intl.NumberFormat("en-BD", { style: "currency", currency: "BDT" });
    const $ = id => document.getElementById(id);

    // ---- Render: draw the page from the state ----
    function render() {
      const income = items.filter(i => i.type === "in").reduce((s, i) => s + i.amount, 0);
      const expense = items.filter(i => i.type === "out").reduce((s, i) => s + i.amount, 0);
      $("income").textContent = money.format(income);
      $("expense").textContent = money.format(expense);
      $("balance").textContent = money.format(income - expense);

      const shown = filter === "all" ? items : items.filter(i => i.type === filter);
      $("list").replaceChildren(...shown.map(item => {
        const li = document.createElement("li");
        li.className = item.type;
        li.dataset.id = item.id;
        const desc = document.createElement("span");
        desc.textContent = item.desc;                       // textContent: safe from HTML injection
        const amt = document.createElement("b");
        amt.className = "amt";
        amt.textContent = (item.type === "in" ? "+" : "-") + money.format(item.amount);
        const del = document.createElement("button");
        del.className = "del";
        del.textContent = "×";
        del.setAttribute("aria-label", "Delete " + item.desc);
        li.append(desc, amt, del);
        return li;
      }));
    }

    // ---- Events ----
    $("form").addEventListener("submit", e => {
      e.preventDefault();
      const desc = $("desc").value.trim();
      const amount = Number($("amount").value);
      if (!desc || !Number.isFinite(amount) || amount <= 0) {
        $("error").textContent = "Enter a description and a positive amount.";
        return;
      }
      $("error").textContent = "";
      items.push({ id: nextId++, desc, amount, type: $("type").value });
      e.target.reset();
      $("desc").focus();
      render();
    });

    // One listener for every delete button (event delegation)
    $("list").addEventListener("click", e => {
      if (!e.target.matches(".del")) return;
      const id = Number(e.target.closest("li").dataset.id);
      items = items.filter(i => i.id !== id);
      render();
    });

    $("filters").addEventListener("click", e => {
      const btn = e.target.closest("button");
      if (!btn) return;
      filter = btn.dataset.filter;
      for (const b of $("filters").children) b.classList.toggle("active", b === btn);
      render();
    });

    render();
  </script>
</body>
</html>

Result

How It Works

1. State

  • All data lives in the items array, plus the current filter. Each item has an id, desc, amount and type ("in" or "out").
  • Amounts are stored as numbers, never as formatted text, so totals are always correct.

2. Render

  • render() calculates income and expenses with filter and reduce, writes the three totals, then rebuilds the list.
  • replaceChildren(...elements) swaps the whole list in one step.
  • Every list item is built with createElement and textContent. If someone types <b>x</b> as a description, it appears as plain text instead of becoming HTML. Building rows with innerHTML and user text would open the door to script injection (XSS).
  • Each <li> carries its item’s id in data-id, so a click can be traced back to the data.

3. Events

  • The form’s submit handler calls preventDefault(), reads the values, and checks them: the description must not be blank, and the amount must be a finite number above zero. Errors appear in an element with role="alert" so screen readers announce them.
  • Valid input is pushed into items, the form is reset, and render() runs. The code never edits the list directly; it changes the state and redraws.
  • Delete buttons are created and destroyed constantly, so instead of adding a listener to each, one listener on the <ul> checks e.target.matches(".del"). This is event delegation. closest("li").dataset.id finds which item to remove.
  • The filter buttons use the same pattern, storing the filter name in data-filter.

Concepts Used

ConceptWhere
Array of objects as stateitems
filter + reduceTotals in render()
Form validationsubmit handler
Event delegationList and filter listeners
dataset attributesdata-id, data-filter
Safe DOM buildingcreateElement + textContent
Intl.NumberFormatmoney.format()
CSS Grid and media querySummary cards and the form layout

Common Mistakes

  1. Changing the page and the data separately, so they drift apart. Change the state, then call render().
  2. Forgetting Number() on input values, so amounts are joined as text.
  3. Using innerHTML with user input.
  4. Using array positions as ids; positions change after a delete. Give each item a lasting id.

Extend the Project

Exercise 1. Save the entries so they survive a page reload.

Show answer
// at the start
items = JSON.parse(localStorage.getItem("expenses") ?? "null") ?? items;
nextId = Math.max(0, ...items.map(i => i.id)) + 1;

// at the end of render()
localStorage.setItem("expenses", JSON.stringify(items));

This works when you open the file in your browser. The live demo above runs in a locked-down frame where storage is not available. See localStorage.

Exercise 2. Show the largest expense under the totals.

Show answer
const biggest = items.filter(i => i.type === "out")
  .toSorted((a, b) => b.amount - a.amount)[0];
$("biggest").textContent = biggest
  ? `Largest expense: ${biggest.desc} (${money.format(biggest.amount)})`
  : "No expenses yet";

Add an element with id="biggest" to the HTML and put this code inside render().

Frequently Asked Questions

Is redrawing the whole list on every change slow?

For lists of a few hundred items, no: the browser handles it easily. Frameworks such as React use the same “state, then render” idea and add clever updates for very large pages.

How would I add categories such as Food and Transport?

Add a category field to each item and a <select> to the form. Then use Object.groupBy(items, i => i.category) to total spending per category.

Summary

  • Keep data in one state object or array.
  • Redraw the page from the state with one render() function.
  • Validate input, build elements safely and use event delegation.
  • Format money only for display with Intl.NumberFormat.

Next: Debugging JavaScript: console Methods and DevTools.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *