Skip to content
Tutorials Center
My learning

Topics

Lesson 129 of 156 Β· Projects

Project: Expense Tracker

Build an expense tracker in plain JavaScript with a validated form, a class for the data, reduce() totals, grouping by category and a CSS bar chart.

Where did the money go this month? An expense tracker answers that question, and building one is a great way to bring the whole course together. You will take input from a form, keep the data in a small class, compute totals with reduce(), group spending by category and draw a bar chart with nothing but CSS.

This is the biggest project of the course. As before, you will build it in stages. Each stage is complete and runnable and adds one idea to the previous one, and the last stage is the finished app.

What you'll build

The finished tracker lets you:

  • add an expense (description, amount, category and date) with a validated form;
  • delete expenses;
  • see the total, the number of expenses, the average and the largest one;
  • see spending by category as a bar chart with amounts and percentages;
  • filter the history by month and sort it by date or amount.

It uses ideas from many lessons: Classes, Private Fields and Static Members, Getters and Setters, Working with Forms, map, filter, reduce and forEach, Array Recipes, Sorting Arrays and Formatting with Intl.

Step 1: The page and its styles

Here is the finished layout, hard-coded. From top to bottom: the form, four summary tiles, the category chart and the history list. Nothing is interactive yet.

Step 1: Markup and styles

The chart deserves a closer look, because it is plain HTML and CSS. Each row sets two CSS custom properties in its style attribute: --share (the bar's width) and --color. One rule, .bar { width: var(--share); background: var(--color); }, draws every bar. Later, JavaScript only has to set those two values.

font-variant-numeric: tabular-nums gives every digit the same width, so amounts line up neatly in columns.

Step 2: The data in a class

Money needs care. In JavaScript, 0.1 + 0.2 is 0.30000000000000004 (see Numbers), and small errors like that pile up when you add hundreds of prices. The standard fix is to store money as whole cents: $64.20 becomes 6420. Adding integers is always exact, and you divide by 100 only when you display a value.

The expenses live in an ExpenseStore class. Its array is a private field (#expenses), so the rest of the app can't change it by accident. The only ways in are add() and remove(), which check their input, and the all getter hands out a copy. Each expense is frozen with Object.freeze(), so even that copy can't be used to change an expense in place.

Dates are stored as "YYYY-MM-DD" strings. They're easy to read, they sort correctly as plain text, and "2026-10-13".slice(0, 7) gives the month. Look at toISODate(), though: it builds the string from local date parts on purpose. new Date().toISOString() uses UTC, which can be a different day in the evening or early morning.

Step 2: An ExpenseStore class and a rendered list

A few things to notice:

  • Intl.NumberFormat with style: "currency" adds the symbol, thousands separators and two decimals. Change "USD" to "EUR" and LOCALE to "de-DE", and you get 64,20 € with no other changes.
  • The sort comparator compares the date strings with localeCompare(). When two expenses share a date, || b.id - a.id breaks the tie, so the one added later comes first.
  • The small el() helper takes care of the repetitive createElement / className / textContent steps. Because it uses textContent, user text is always shown as plain text and never run as HTML.

Step 3: Adding and deleting expenses

Now the form works. Most of the checking happens in HTML before your code runs: required, min="0.01" and step="0.01" on the amount, maxlength on the description, and a max date of today, which the script sets. The browser won't fire submit until every field passes, and it shows its own messages. See form validation.

One check needs JavaScript: a description of only spaces passes required. The handler trims it and, if nothing is left, uses setCustomValidity() to show a message in the same style as the browser's own.

Reading the form takes one line: Object.fromEntries(new FormData(form)) turns the fields into a plain object keyed by their name attributes. Then the amount becomes cents with Math.round(Number(amount) * 100). The Math.round() is important: 19.99 * 100 is 1998.9999999999998, not 1999.

Deleting uses event delegation: one listener on the list finds the clicked row's data-id.

Step 3: A validated form and delete buttons

Try to break it. Leave fields empty, type -5 or 3.999 as the amount, pick a date in the future, or enter only spaces as the description. Each time you get a clear message, and nothing reaches the store. If an invalid value ever did get through, the RangeError inside add() would stop it. Checking at the edge and again inside the class is cheap insurance.

Step 4: Totals with reduce()

Now for the numbers. reduce() walks through an array while carrying one value along, and here it does two different jobs:

  • Sum: start at 0, and add each expense's cents.
  • Largest: start at null, and keep whichever expense is bigger, the one carried so far or the current one.

These calculations are plain functions that take an array. They don't read the store or the page. That keeps them easy to test in the console, and in step 6 they will work on a filtered month without any changes.

Step 4: Summary tiles with reduce()

Two edge cases are handled on purpose. With no expenses, the average would be 0 / 0, which is NaN, so summarize() checks count first. And the "largest" reduce starts from null, because an empty list has no largest expense. The tiles then show a dash instead of "$NaN".

Delete every expense to see both edge cases in action.

Step 5: Grouping by category and a CSS bar chart

To chart spending by category, you first group the expenses: one bucket of expenses per category. Object.groupBy() does exactly that. Then map() turns each bucket into one row (category, total, count), and toSorted() puts the biggest spender first.

Object.groupBy() is part of ES2024 and works in all current browsers. For older browsers, the code falls back to a short reduce() that builds the same kind of object. ??= ("assign if nullish") creates each bucket the first time a category appears.

Each chart row is a list item with text and a decorative bar. The bar's width is the category's share of the total, set as the --share custom property. Screen readers skip the bar (aria-hidden="true") but still read the label, amount and percentage, so the chart works without seeing it.

Step 5: Group by category and draw a chart

Add a large "Fun" expense and watch the chart reorder itself. All the chart code does is set two custom properties per row. Layout, colors and widths stay in CSS, where they belong.

The chart reuses stats.total from summarize() instead of adding everything up a second time. The total is never zero when there are rows, because every expense is at least one cent. That's why total / grandTotal is safe here.

Step 6: Months and sorting: the finished tracker

The last feature makes the tracker useful over time: a month filter and a sort order for the history. These are view settings, not data, so they live in a small view object next to the store:

  • The month menu is built from the data itself. new Set(...) collects each distinct "YYYY-MM" key (see Sets), and new Option(text, value) creates each <option>. Month names come from Intl.DateTimeFormat.
  • The sort orders are a lookup table of comparator functions, SORTERS, so the <select> value picks the function directly.
  • The summary, chart and list all use the same filtered array. The calculations from steps 4 and 5 work on it unchanged, because they only ever received an array.
Step 6: The complete expense tracker

Look at how little the final step changed. The calculations, the chart and the row rendering are the same code as before. The new feature only decides which array they get. Small functions that take data in and give results back are easy to reuse like this.

[...new Set(...)].toSorted().reverse() gives the months newest first, because "YYYY-MM" strings sort in date order. renderMonthOptions() also takes care of a quiet edge case: if you delete the last expense of the month you're viewing, that month disappears from the menu, and the view falls back to "All time" instead of showing an empty, unselectable month.

Extension: split it into modules

In a real project, this script would not be one long <script> block. Modules let you give each part its own file, and the pieces you built are already shaped for that:

JavaScript
// format.js
export const LOCALE = "en-US";
const money = new Intl.NumberFormat(LOCALE, { style: "currency", currency: "USD" });
export const formatMoney = (cents) => money.format(cents / 100);

// expense-store.js
import { CATEGORIES } from "./categories.js";
export class ExpenseStore { /* … the same class … */ }

// stats.js: pure functions, easy to unit test
export const sumCents = (expenses) => expenses.reduce((sum, e) => sum + e.amountCents, 0);
export function summarize(expenses) { /* … */ }
export function totalsByCategory(expenses) { /* … */ }

// main.js: the only file that touches the page
import { ExpenseStore } from "./expense-store.js";
import { summarize, totalsByCategory } from "./stats.js";
import { formatMoney } from "./format.js";
// … rendering and event listeners …

Load the entry file with <script type="module" src="main.js"></script>, and the browser fetches the rest. Notice that only main.js knows about the DOM. You could reuse the store and the stats in a Node.js script or a test runner without changes.

Extension: keep expenses between visits

The sandbox blocks storage, so this can't run here. In your own copy, localStorage can keep the expenses between visits (see localStorage and sessionStorage). Add two methods to the class and call save() at the end of render():

JavaScript
class ExpenseStore {
  // … everything from before …

  toJSON() {
    return this.#expenses; // JSON.stringify(store) uses this
  }

  static fromJSON(text) {
    const store = new ExpenseStore();
    for (const item of JSON.parse(text) ?? []) {
      try {
        store.add(item); // add() validates every saved item again
      } catch {
        console.warn("Skipped a damaged expense:", item);
      }
    }
    return store;
  }
}

const KEY = "expenses";
let store;
try {
  store = ExpenseStore.fromJSON(localStorage.getItem(KEY));
} catch {
  store = new ExpenseStore(); // storage blocked or data corrupted
}

function save() {
  try {
    localStorage.setItem(KEY, JSON.stringify(store));
  } catch {
    // storage full or blocked: the app keeps working in memory
  }
}

Because fromJSON() sends every saved item through add(), damaged or hand-edited data is checked by the same rules as the form. JSON.parse(null) returns null on a first visit, and ?? [] turns that into an empty list. Ids are renumbered on load, which is fine because they only link rows on the page to items in memory.

More ideas to try

  • Budgets: give each category a monthly limit and color the bar red when spending goes over it.
  • Undo: keep the last deleted expense and show an "Undo" button for a few seconds with setTimeout().
  • Export: build a CSV string from store.all and offer it as a download with a Blob URL.
  • Editing: double-click a row to load it back into the form, as in the to-do app.
  • Several currencies: store a currency code with each expense and format each one with its own Intl.NumberFormat.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. Why does the tracker store money as whole cents?

    Adding integers never produces rounding errors such as 0.30000000000000004. Divide by 100 only when you display a value.
  2. 2. What does #expenses inside the ExpenseStore class mean?

    Private fields can't be reached from outside, so the only ways to change the data are the validated add() and remove() methods.
  3. 3. In expenses.reduce((sum, e) => sum + e.amountCents, 0), what is the 0?

    The accumulator starts at 0 and each expense's cents are added to it. Without it, reduce() on an empty array throws a TypeError.
  4. 4. How does the CSS bar chart set each bar's width?

    JavaScript only sets --share and --color, and one CSS rule turns them into a bar. Layout and styling stay in CSS.
  5. 5. Why does Math.round(Number(data.amount) * 100) need Math.round()?

    Floating-point multiplication can land just next to the whole number you expect. Rounding gives the exact number of cents, which add() checks with Number.isInteger().

Summary

  • Store money as integer cents, and format it only at display time with Intl.NumberFormat and style: "currency".
  • A class with private fields and validated methods keeps the data safe. Getters can hand out copies, and frozen items can't be changed in place.
  • Let HTML validation do most of the form checking, read fields with FormData, and use setCustomValidity() for the rules HTML can't express.
  • reduce() computes sums, maximums and groups. Object.groupBy() groups in one call, with a reduce() fallback for older browsers.
  • A bar chart can be pure CSS: set a custom property per row, and let one rule draw every bar.
  • Keep calculations as small functions that take an array, so filters and new views can reuse them without changes.

Congratulations! You started with your first console.log() and finished with complete apps that use classes, async code, the DOM and Intl. A few smaller projects follow, then classic data structures and algorithms and the practice chapter. Next: Project: Five Mini DOM Apps.