Lesson 91 of 296
Project: a to-do list in plain JavaScript
On this page
What you will build
A to-do list app with no frameworks:
- Add a task
- Mark a task as done or not done
- Delete a task
- Filter: all, active, done
- Show how many tasks are left
- Save everything in localStorage so it survives a refresh
- Keyboard and screen reader friendly
This is a very common take-home task and a common 45-minute live coding task. It tests the DOM, events, delegation, state and storage together.
The plan
A clean way to build interactive pages, and the same idea React uses:
- Keep all the data in one JavaScript array (the state). The state is the single source of truth.
- Write one
render()function that builds the page from the state. - When the user does something: update the state, save it, call
render().
Never read data back from the DOM to work out the state. The DOM only shows the state.
The HTML
<main class="todo-app">
<h1>My tasks</h1>
<form id="todo-form">
<label for="todo-input">New task</label>
<input id="todo-input" name="title" type="text" required maxlength="200" autocomplete="off">
<button type="submit">Add</button>
</form>
<div class="filters" role="group" aria-label="Filter tasks">
<button type="button" data-filter="all" aria-pressed="true">All</button>
<button type="button" data-filter="active" aria-pressed="false">Active</button>
<button type="button" data-filter="done" aria-pressed="false">Done</button>
</div>
<ul id="todo-list"></ul>
<p id="todo-count" aria-live="polite"></p>
</main>
<script src="app.js" defer></script>- A real
<form>and<label>, so Enter works and screen readers announce the field (Lesson 10). aria-pressedtells screen readers which filter is active (Lesson 13).aria-live="polite"makes screen readers announce the count when it changes.deferso the script runs after the HTML is parsed (Lesson 86).
The JavaScript
const STORAGE_KEY = "todos-v1";
const form = document.getElementById("todo-form");
const input = document.getElementById("todo-input");
const list = document.getElementById("todo-list");
const count = document.getElementById("todo-count");
const filterButtons = document.querySelectorAll("[data-filter]");
let todos = loadTodos();
let currentFilter = "all";
function loadTodos() {
try {
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY));
return Array.isArray(saved) ? saved : [];
} catch {
return [];
}
}
function saveTodos() {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(todos));
} catch {
console.warn("Could not save tasks");
}
}
function getVisibleTodos() {
if (currentFilter === "active") return todos.filter((t) => !t.done);
if (currentFilter === "done") return todos.filter((t) => t.done);
return todos;
}
function render() {
const fragment = document.createDocumentFragment();
for (const todo of getVisibleTodos()) {
const li = document.createElement("li");
li.dataset.id = todo.id;
li.className = todo.done ? "todo done" : "todo";
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = todo.done;
checkbox.id = `todo-${todo.id}`;
checkbox.className = "toggle";
const label = document.createElement("label");
label.htmlFor = checkbox.id;
label.textContent = todo.title;
const deleteButton = document.createElement("button");
deleteButton.type = "button";
deleteButton.className = "delete";
deleteButton.textContent = "Delete";
deleteButton.setAttribute("aria-label", `Delete ${todo.title}`);
li.append(checkbox, label, deleteButton);
fragment.append(li);
}
list.replaceChildren(fragment);
const left = todos.filter((t) => !t.done).length;
count.textContent = `${left} ${left === 1 ? "task" : "tasks"} left`;
filterButtons.forEach((btn) => {
btn.setAttribute("aria-pressed", String(btn.dataset.filter === currentFilter));
});
}
function update(newTodos) {
todos = newTodos;
saveTodos();
render();
}
form.addEventListener("submit", (e) => {
e.preventDefault();
const title = input.value.trim();
if (!title) return;
update([...todos, { id: crypto.randomUUID(), title, done: false }]);
form.reset();
input.focus();
});
list.addEventListener("change", (e) => {
if (!e.target.matches(".toggle")) return;
const id = e.target.closest("li").dataset.id;
update(todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
});
list.addEventListener("click", (e) => {
const button = e.target.closest(".delete");
if (!button) return;
const id = button.closest("li").dataset.id;
update(todos.filter((t) => t.id !== id));
});
filterButtons.forEach((btn) => {
btn.addEventListener("click", () => {
currentFilter = btn.dataset.filter;
render();
});
});
render();How it works, part by part
State: todos is an array of { id, title, done }. currentFilter is "all", "active" or "done".
Loading: loadTodos reads from localStorage inside try...catch, and checks the result is really an array, so corrupted or missing data gives an empty list instead of a crash (Lesson 90).
IDs: crypto.randomUUID() creates a unique ID (supported in modern browsers on HTTPS and localhost). IDs, not array positions, identify tasks, because positions change when you filter or delete.
Rendering:
- Builds every item in a DocumentFragment, then
replaceChildrenswaps the whole list in one operation (Lesson 87). - Uses
textContentfor the title, so a task called<img onerror=...>is shown as text, not run (XSS protection). - Each checkbox has a matching
label, so clicking the text toggles it, and screen readers read it. - The delete button's
aria-labelsays which task it deletes; otherwise a screen reader hears "Delete, Delete, Delete".
Updating: every change creates a new array ([...todos, ...], map, filter) instead of mutating the old one (Lesson 48). This is exactly the pattern React requires.
Events:
- The form's
submithandles both the button and the Enter key.preventDefaultstops the page reloading. - Event delegation (Lesson 88): one
changelistener and oneclicklistener on the<ul>handle every task, including tasks added later.closest("li")finds the task's ID from the clicked element. - The checkbox uses the
changeevent, which also fires when toggled with the keyboard.
Testing checklist
Before you say "done" in an interview, check:
- Adding an empty task or only spaces does nothing.
- Adding a task with
<b>bold</b>shows the tags as text. - Toggle, delete and each filter work.
- Deleting while a filter is active deletes the right task.
- The count says "1 task" and "2 tasks" correctly.
- Refresh: tasks are still there.
- Corrupted storage: run
localStorage.setItem("todos-v1", "rubbish")in the console and refresh; the app should start empty, not crash. - Keyboard only: Tab to every control; Enter adds; Space toggles; Enter on Delete deletes.
Extensions interviewers ask for
- Edit a task on double click: replace the label with an input; save on Enter or blur; cancel on Escape.
- "Clear completed" button:
update(todos.filter((t) => !t.done)). - Sync tabs: listen for the
storageevent and re-load and re-render. - Save to a server: replace
saveTodoswithfetchcalls (Lesson 89). Discuss optimistic updates: update the page first, then roll back if the request fails. - Performance with thousands of tasks: only update changed items instead of re-rendering everything, or use virtualisation (only render visible rows). This is the problem React's reconciliation solves (Part 12).
Common mistakes
- Using
innerHTMLwith the task title (XSS). - Adding a listener to every task.
- Using the array index as the ID.
- Reading state from the DOM (for example, counting
.doneelements to get the count). - Forgetting
preventDefaulton the form. - Not handling bad localStorage data.
How to say it in an interview
"I keep the todos in one array as the single source of truth, and a render function rebuilds the list from that state in a DocumentFragment. Every action updates the state immutably, saves it to localStorage inside try-catch, and re-renders. I use one delegated change listener and one click listener on the list, finding the item's ID with closest, so new items need no extra listeners. Titles go in with textContent to prevent XSS, IDs come from crypto.randomUUID rather than array indexes, and the form, labels, aria-pressed and aria-live keep it accessible. This is the same state-then-render model React uses."
Key words
| Word | Meaning |
|---|---|
| State | The data that describes what the app should show |
| Single source of truth | One place that holds the real data |
| Render | Build the page from the state |
| Immutable update | Creating a new array or object instead of changing the old one |
| Optimistic update | Updating the screen before the server confirms |
| Virtualisation | Rendering only the rows visible on screen |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.