JavaScript Mini Project
Let's put the whole course together and build a small but complete app: an expense tracker. You'll add expenses, see totals per category, filter the list, and delete entries. We'll build it in steps — first the pure logic as plain JavaScript you can test in the console, then the user interface on top of it.
What it uses:
| Feature | Chapters |
|---|---|
| Objects and arrays of objects | Objects, Arrays |
map, filter, reduce, sort |
Array Iteration, Array Sort |
| Validation with thrown errors | Errors |
| A class with private state | Classes, Getters & Setters |
| Number and date formatting | Number Methods, Dates |
| DOM rendering and event delegation | HTML DOM |
| Safe storage with a fallback | Web Storage |
Step 1: the data model
Each expense is a plain object. A small factory function creates one, so every expense has the same shape. We keep amounts in cents to avoid floating-point rounding errors, and dates as YYYY-MM-DD strings, which sort correctly as text:
let nextId = 1;
function createExpense(description, amount, category, date) {
return {
id: nextId++,
description: description.trim(),
cents: Math.round(amount * 100),
category,
date,
};
}
const expenses = [
createExpense("Groceries ", 54.2, "food", "2025-03-02"),
createExpense("Bus pass", 30, "transport", "2025-03-01"),
createExpense("Cinema", 12.5, "fun", "2025-03-07"),
createExpense("Pizza", 18.9, "food", "2025-03-07"),
];
console.log(expenses[0]);
console.log(expenses.length, "expenses");{
id: 1,
description: 'Groceries',
cents: 5420,
category: 'food',
date: '2025-03-02'
}
4 expenses
Step 2: summaries with reduce
Now the useful numbers: the grand total and a total per category. A small formatMoney helper converts cents back into a readable string:
const expenses = [
{ id: 1, description: "Groceries", cents: 5420, category: "food", date: "2025-03-02" },
{ id: 2, description: "Bus pass", cents: 3000, category: "transport", date: "2025-03-01" },
{ id: 3, description: "Cinema", cents: 1250, category: "fun", date: "2025-03-07" },
{ id: 4, description: "Pizza", cents: 1890, category: "food", date: "2025-03-07" },
];
const formatMoney = (cents) => (cents / 100).toFixed(2) + " €";
const total = expenses.reduce((sum, e) => sum + e.cents, 0);
const byCategory = expenses.reduce((acc, e) => {
acc[e.category] = (acc[e.category] ?? 0) + e.cents;
return acc;
}, {});
console.log("Total:", formatMoney(total));
for (const [category, cents] of Object.entries(byCategory).sort((a, b) => b[1] - a[1])) {
const share = Math.round((cents / total) * 100);
console.log(`${category.padEnd(10)} ${formatMoney(cents).padStart(9)} ${"█".repeat(share / 5)} ${share}%`);
}Total: 115.60 €
food 73.10 € ████████████ 63%
transport 30.00 € █████ 26%
fun 12.50 € ██ 11%
("█".repeat(12.6) rounds down — repeat truncates its argument.)
Step 3: validation
User input can be anything. Before creating an expense, validate it and throw an error with a helpful message. The caller catches it and shows the message:
const CATEGORIES = ["food", "transport", "fun", "home", "other"];
function validate({ description, amount, category, date }) {
if (!description || description.trim().length < 2) {
throw new Error("Description needs at least 2 characters");
}
const value = Number(amount);
if (!Number.isFinite(value) || value <= 0) {
throw new Error(`Amount must be a positive number, got "${amount}"`);
}
if (!CATEGORIES.includes(category)) {
throw new Error(`Unknown category "${category}"`);
}
if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || Number.isNaN(new Date(date + "T00:00:00Z").getTime())) {
throw new Error(`Invalid date "${date}"`);
}
return { description: description.trim(), amount: value, category, date };
}
const inputs = [
{ description: "Coffee", amount: "3.20", category: "food", date: "2025-03-08" },
{ description: "x", amount: "5", category: "food", date: "2025-03-08" },
{ description: "Taxi", amount: "-12", category: "transport", date: "2025-03-08" },
{ description: "Lamp", amount: "25", category: "furniture", date: "2025-03-08" },
{ description: "Book", amount: "9.99", category: "fun", date: "2025-13-40" },
];
for (const input of inputs) {
try {
console.log("ok:", validate(input));
} catch (err) {
console.log("rejected:", err.message);
}
}ok: {
description: 'Coffee',
amount: 3.2,
category: 'food',
date: '2025-03-08'
}
rejected: Description needs at least 2 characters
rejected: Amount must be a positive number, got "-12"
rejected: Unknown category "furniture"
rejected: Invalid date "2025-13-40"
Step 4: a class to hold it all
Let's wrap the logic in an ExpenseTracker class. The list is private, so the only way to change it is through methods that validate input. Methods return new arrays rather than exposing the internal one:
class ExpenseTracker {
#expenses = [];
#nextId = 1;
add(description, amount, category, date) {
if (!(amount > 0)) throw new Error("Amount must be positive");
const expense = { id: this.#nextId++, description, cents: Math.round(amount * 100), category, date };
this.#expenses.push(expense);
return expense;
}
remove(id) {
const before = this.#expenses.length;
this.#expenses = this.#expenses.filter((e) => e.id !== id);
return this.#expenses.length < before;
}
list({ category = "all", newestFirst = true } = {}) {
return this.#expenses
.filter((e) => category === "all" || e.category === category)
.toSorted((a, b) => (newestFirst ? b.date.localeCompare(a.date) : a.date.localeCompare(b.date)) || a.id - b.id);
}
get totalCents() {
return this.#expenses.reduce((sum, e) => sum + e.cents, 0);
}
}
const tracker = new ExpenseTracker();
tracker.add("Bus pass", 30, "transport", "2025-03-01");
tracker.add("Groceries", 54.2, "food", "2025-03-02");
const pizza = tracker.add("Pizza", 18.9, "food", "2025-03-07");
tracker.add("Cinema", 12.5, "fun", "2025-03-07");
const show = (list) => list.map((e) => `${e.date} ${e.description}`).join(" | ");
console.log(show(tracker.list()));
console.log(show(tracker.list({ category: "food", newestFirst: false })));
console.log(tracker.remove(pizza.id), tracker.remove(999));
console.log((tracker.totalCents / 100).toFixed(2));2025-03-07 Pizza | 2025-03-07 Cinema | 2025-03-02 Groceries | 2025-03-01 Bus pass
2025-03-02 Groceries | 2025-03-07 Pizza
true false
96.70
Step 5: the user interface
Finally, connect the logic to the page. The app follows a simple, reliable pattern:
- State lives in one place (the expenses array).
- A single
render()function rebuilds the visible list and totals from the state. - Event handlers only change the state and then call
render().
Delete buttons use event delegation (one listener on the list), the form uses preventDefault() and validation, and saving uses the safe storage wrapper from the Web Storage chapter — in this sandboxed playground it falls back to memory, but on a real site the data survives reloads.
<style>
body { font-family: system-ui, sans-serif; max-width: 560px; margin: 12px auto; padding: 0 8px; }
form { display: grid; grid-template-columns: 2fr 1fr 1fr; gap: 6px; }
form input, form select, form button { padding: 6px; font: inherit; }
form button { grid-column: 1 / -1; background: #f0db4f; border: 0; border-radius: 6px; cursor: pointer; }
.error { color: crimson; min-height: 1.3em; margin: 4px 0; }
.toolbar { display: flex; justify-content: space-between; align-items: center; margin: 8px 0; }
ul { list-style: none; padding: 0; margin: 0; }
li { display: grid; grid-template-columns: 90px 1fr auto auto; gap: 8px; align-items: center; padding: 6px 4px; border-bottom: 1px solid #eee; }
.cat { font-size: .8em; padding: 1px 6px; border-radius: 10px; background: #eef; }
.amount { font-variant-numeric: tabular-nums; }
.del { border: 0; background: none; cursor: pointer; color: #999; }
.del:hover { color: crimson; }
.bars div { display: flex; gap: 6px; align-items: center; font-size: .9em; }
.bars span.bar { height: 10px; background: #f0db4f; border-radius: 4px; }
.empty { color: #888; padding: 12px 4px; }
</style>
<h2>💸 Expense tracker</h2>
<form id="form" novalidate>
<input name="description" placeholder="Description" required>
<input name="amount" type="number" step="0.01" min="0.01" placeholder="Amount €" required>
<select name="category">
<option value="food">food</option><option value="transport">transport</option>
<option value="fun">fun</option><option value="home">home</option><option value="other">other</option>
</select>
<input name="date" type="date" value="2025-03-08" style="grid-column: 1 / 3">
<button>Add expense</button>
</form>
<p class="error" id="error"></p>
<div class="toolbar">
<label>Show
<select id="filter">
<option value="all">all categories</option><option value="food">food</option>
<option value="transport">transport</option><option value="fun">fun</option>
<option value="home">home</option><option value="other">other</option>
</select>
</label>
<strong id="total"></strong>
</div>
<ul id="list"></ul>
<h3>By category</h3>
<div class="bars" id="bars"></div>
<script type="module">
// ---- storage with a graceful fallback ----
const memory = new Map();
const storage = {
load(key, fallback) {
try {
const raw = localStorage.getItem(key);
return raw === null ? fallback : JSON.parse(raw);
} catch {
return memory.has(key) ? memory.get(key) : fallback;
}
},
save(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {
memory.set(key, value);
}
},
};
// ---- state ----
const CATEGORIES = ["food", "transport", "fun", "home", "other"];
let expenses = storage.load("expenses", [
{ id: 1, description: "Bus pass", cents: 3000, category: "transport", date: "2025-03-01" },
{ id: 2, description: "Groceries", cents: 5420, category: "food", date: "2025-03-02" },
{ id: 3, description: "Cinema", cents: 1250, category: "fun", date: "2025-03-07" },
]);
let filter = "all";
const $ = (sel) => document.querySelector(sel);
const money = (cents) => (cents / 100).toFixed(2) + " €";
// ---- logic ----
function validate({ description, amount, category, date }) {
if (description.trim().length < 2) throw new Error("Description needs at least 2 characters");
const value = Number(amount);
if (!Number.isFinite(value) || value <= 0) throw new Error("Amount must be a positive number");
if (!CATEGORIES.includes(category)) throw new Error("Pick a category");
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new Error("Pick a date");
return { description: description.trim(), cents: Math.round(value * 100), category, date };
}
function addExpense(data) {
const id = Math.max(0, ...expenses.map((e) => e.id)) + 1;
expenses = [...expenses, { id, ...validate(data) }];
storage.save("expenses", expenses);
}
function removeExpense(id) {
expenses = expenses.filter((e) => e.id !== id);
storage.save("expenses", expenses);
}
// ---- rendering ----
function render() {
const visible = expenses
.filter((e) => filter === "all" || e.category === filter)
.toSorted((a, b) => b.date.localeCompare(a.date) || b.id - a.id);
const list = $("#list");
if (visible.length === 0) {
list.innerHTML = '<li class="empty">No expenses yet.</li>';
} else {
list.replaceChildren(
...visible.map((e) => {
const li = document.createElement("li");
li.dataset.id = e.id;
li.innerHTML = '<span></span><span></span><span class="amount"></span><button class="del" title="Delete">✕</button>';
const [date, desc, amount] = li.children;
date.textContent = e.date;
desc.textContent = e.description + " ";
const tag = document.createElement("span");
tag.className = "cat";
tag.textContent = e.category;
desc.append(tag);
amount.textContent = money(e.cents);
return li;
})
);
}
const total = visible.reduce((sum, e) => sum + e.cents, 0);
$("#total").textContent = `Total: ${money(total)}`;
const byCat = expenses.reduce((acc, e) => ((acc[e.category] = (acc[e.category] ?? 0) + e.cents), acc), {});
const max = Math.max(1, ...Object.values(byCat));
$("#bars").replaceChildren(
...Object.entries(byCat)
.sort((a, b) => b[1] - a[1])
.map(([cat, cents]) => {
const row = document.createElement("div");
row.innerHTML = `<span style="width:80px">${cat}</span><span class="bar" style="width:${(cents / max) * 200}px"></span><span>${money(cents)}</span>`;
return row;
})
);
}
// ---- events ----
$("#form").addEventListener("submit", (event) => {
event.preventDefault();
const form = event.currentTarget;
try {
addExpense(Object.fromEntries(new FormData(form)));
$("#error").textContent = "";
form.description.value = "";
form.amount.value = "";
form.description.focus();
render();
} catch (err) {
$("#error").textContent = err.message;
}
});
$("#list").addEventListener("click", (event) => {
if (!event.target.matches(".del")) return;
const id = Number(event.target.closest("li").dataset.id);
removeExpense(id);
render();
});
$("#filter").addEventListener("change", (event) => {
filter = event.target.value;
render();
});
render();
console.log("Expense tracker ready with", expenses.length, "expenses");
</script>Ideas to extend it
Try adding these features yourself — each one practises a chapter from the course:
- Edit an expense by double-clicking it (events, forms).
- Monthly view: group expenses by
date.slice(0, 7)and show one total per month (reduce, Maps). - Budget warning: set a monthly budget and turn the total red when it's exceeded (
classList). - Export to JSON: show
JSON.stringify(expenses, null, 2)in a<pre>so the user can copy it (JSON). - Sort options: by date, amount or description (
sortwith compare functions). - Undo delete: keep the last removed expense and offer a 5-second "Undo" button (
setTimeout,clearTimeout).
Test yourself
Why does the tracker store amounts in cents?
- Cents use less memory
- Integer cents avoid floating-point rounding errors like 0.1 + 0.2
- JSON can't store decimals
- toFixed only works on integers
Why is one click listener on the <ul> enough for all delete buttons?
- Buttons can't have listeners
- Click events bubble up, so the list sees clicks on any child (event delegation)
- The browser copies listeners to new elements
- innerHTML adds listeners automatically
In the app's pattern, what should an event handler do?
- Edit the DOM directly in many places
- Update the state, then call render()
- Reload the page
- Save to storage only