Skip to content

Lesson 24 of 50JavaScript in the browser

Project: A To-Do App in Plain JavaScript

Build a complete to-do app with plain HTML, CSS and JavaScript, stage by stage, then see what a framework like React would do for you.

22 min read0/5 questions

Time to put the last three lessons together. You will build a to-do app with no libraries at all: add tasks, tick them off, delete them, filter them, and keep them after a reload. It is a small app, but it has the same moving parts as a large one: data, events, rendering and storage. Building it by hand once is the best way to understand what front-end frameworks are for, which is exactly where this lesson ends.

Each stage below is a complete, working app in its own live editor. You can read them in order, or jump to any stage and start playing.

The plan: state, events, render

Before writing code, decide where the truth lives. A beginner's to-do app often keeps it in the DOM: to know if a task is done, it checks whether the li has a done class. That gets messy fast, because every feature has to read and patch the page in a different way.

The cleaner design, and the one every modern framework uses, has three parts:

  • State: a plain JavaScript array of task objects, like { id: "k3x9", text: "Buy milk", done: false }. This is the single source of truth.
  • Event handlers: they never touch the list on the page. They only change the state, then ask for a render.
  • A render function: it throws away the old list and rebuilds it from the state. Whatever the state says, the page shows.
One direction of data
User: clicks, typesUserclicks, typesHandler: addEventListenerHandleraddEventListenerState: the todos arrayStatethe todos arraylocalStorage: survives reloadslocalStoragesurvives reloadsrender(): state to DOMrender()state to DOMPage: the DOMPagethe DOMeventupdatesavereadrebuildsees

The user does something. A listener (usually one delegated listener) receives the event.

1/5

Stage 1: add tasks

The skeleton is a form with one text field, an empty list, and a short script. Using a real form means the Enter key works for free and the required attribute stops empty tasks before your code even runs.

HTML & CSS
<style> body { max-width: 420px; } form { display: flex; gap: 8px; } input[type="text"] { flex: 1; font: inherit; padding: 6px 8px; } button { font: inherit; padding: 6px 12px; } ul { list-style: none; padding: 0; } li { padding: 8px 4px; border-bottom: 1px solid #e5e5e5; }</style> <h2>To do</h2><form id="new-todo"> <label for="todo-text" hidden>New task</label> <input id="todo-text" type="text" name="text" placeholder="What needs doing?" required autocomplete="off"> <button>Add</button></form><ul id="list"></ul> <script> const todos = []; // A short random id, like "lq3x9k2f": time plus a few random characters function newId() { return Date.now().toString(36) + Math.random().toString(36).slice(2, 6); } const form = document.getElementById("new-todo"); const list = document.getElementById("list"); function render() { list.replaceChildren( ...todos.map((todo) => { const li = document.createElement("li"); li.textContent = todo.text; // textContent, so typed HTML stays harmless return li; }) ); } form.addEventListener("submit", (event) => { event.preventDefault(); const text = form.elements.text.value.trim(); if (!text) return; todos.push({ id: newId(), text, done: false }); form.reset(); render(); }); render();</script>

Preview

Add three tasks. Try adding <b>hi</b> as a task: it shows as text, because render uses textContent. Then try a task that is only spaces: required lets it through (spaces count as a value), but trim() catches it.

Each task gets an id from newId, built from the current time plus a few random characters so two tasks added in the same millisecond still differ. In a real app you could use crypto.randomUUID(), which is built into modern browsers on secure (HTTPS) pages.

Notice render does not add one li; it rebuilds the whole list with replaceChildren. That feels wasteful, and for a huge list it would be, but for a to-do list it is instant and it removes a whole category of bugs.

Quick check
In this design, the user ticks a task as done. What should the click handler do?
Need a nudge? A hint rules out a wrong answer.

Stage 2: complete and delete

Each task now gets a checkbox and a delete button. Rather than adding listeners to every row (rows are rebuilt on each render, so their listeners would be thrown away anyway), there is one delegated listener on the list. Each li carries its task's id in a data-id attribute, so the handler knows which task was hit.

Why an id and not the array position? Positions shift when you delete or filter. An id stays attached to its task forever.

HTML & CSS
<style> body { max-width: 420px; } form { display: flex; gap: 8px; } input[type="text"] { flex: 1; font: inherit; padding: 6px 8px; } button { font: inherit; padding: 6px 12px; } ul { list-style: none; padding: 0; } li { display: flex; align-items: center; gap: 8px; padding: 6px 4px; border-bottom: 1px solid #e5e5e5; } li label { flex: 1; } li.done label { text-decoration: line-through; color: #777; } .delete { padding: 2px 8px; font-size: 13px; }</style> <h2>To do</h2><form id="new-todo"> <label for="todo-text" hidden>New task</label> <input id="todo-text" type="text" name="text" placeholder="What needs doing?" required autocomplete="off"> <button>Add</button></form><ul id="list"></ul> <script> const todos = [ { id: "a", text: "Water the plants", done: false }, { id: "b", text: "Reply to Sam", done: true }, ]; // A short random id, like "lq3x9k2f": time plus a few random characters function newId() { return Date.now().toString(36) + Math.random().toString(36).slice(2, 6); } const form = document.getElementById("new-todo"); const list = document.getElementById("list"); function renderItem(todo) { const li = document.createElement("li"); li.dataset.id = todo.id; li.classList.toggle("done", todo.done); const label = document.createElement("label"); const box = document.createElement("input"); box.type = "checkbox"; box.checked = todo.done; label.append(box, " ", todo.text); // strings passed to append become text nodes const del = document.createElement("button"); del.className = "delete"; del.textContent = "Delete"; del.setAttribute("aria-label", `Delete ${todo.text}`); li.append(label, del); return li; } function render() { list.replaceChildren(...todos.map(renderItem)); } form.addEventListener("submit", (event) => { event.preventDefault(); const text = form.elements.text.value.trim(); if (!text) return; todos.push({ id: newId(), text, done: false }); form.reset(); render(); }); list.addEventListener("change", (event) => { const id = event.target.closest("li").dataset.id; const todo = todos.find((t) => t.id === id); todo.done = event.target.checked; render(); }); list.addEventListener("click", (event) => { if (!event.target.closest(".delete")) return; const id = event.target.closest("li").dataset.id; const index = todos.findIndex((t) => t.id === id); todos.splice(index, 1); render(); }); render();</script>

Preview

Tick, untick and delete a few tasks, then add new ones and check they work too. Each row's checkbox is wrapped in a label, so clicking the text toggles it, and each Delete button has an aria-label naming its task, so a screen reader user hears "Delete Water the plants" instead of five identical "Delete" buttons.

Put it in order5 steps

A user clicks Delete on a task. Put what happens in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Stage 3: filters and a counter

Now add All, Active and Done filters, a count of tasks left, and a Clear done button. The interesting part is what you do not add: the filter is just another piece of state, a string. render reads it and shows a filtered copy of the array. The original array is never changed by filtering, so switching back to All loses nothing.

HTML & CSS
<style> body { max-width: 420px; } form, .filters { display: flex; gap: 8px; } input[type="text"] { flex: 1; font: inherit; padding: 6px 8px; } button { font: inherit; padding: 6px 12px; } ul { list-style: none; padding: 0; } li { display: flex; align-items: center; gap: 8px; padding: 6px 4px; border-bottom: 1px solid #e5e5e5; } li label { flex: 1; } li.done label { text-decoration: line-through; color: #777; } .delete { padding: 2px 8px; font-size: 13px; } .filters button[aria-pressed="true"] { background: #111; color: white; } footer { display: flex; justify-content: space-between; align-items: center; margin-top: 8px; }</style> <h2>To do</h2><form id="new-todo"> <label for="todo-text" hidden>New task</label> <input id="todo-text" type="text" name="text" placeholder="What needs doing?" required autocomplete="off"> <button>Add</button></form><div class="filters" id="filters"> <button data-filter="all">All</button> <button data-filter="active">Active</button> <button data-filter="done">Done</button></div><ul id="list"></ul><footer> <span id="count" aria-live="polite"></span> <button id="clear">Clear done</button></footer> <script> let todos = [ { id: "a", text: "Water the plants", done: false }, { id: "b", text: "Reply to Sam", done: true }, { id: "c", text: "Book the dentist", done: false }, ]; let filter = "all"; // A short random id, like "lq3x9k2f": time plus a few random characters function newId() { return Date.now().toString(36) + Math.random().toString(36).slice(2, 6); } const form = document.getElementById("new-todo"); const list = document.getElementById("list"); const FILTERS = { all: () => true, active: (todo) => !todo.done, done: (todo) => todo.done, }; function renderItem(todo) { const li = document.createElement("li"); li.dataset.id = todo.id; li.classList.toggle("done", todo.done); const label = document.createElement("label"); const box = document.createElement("input"); box.type = "checkbox"; box.checked = todo.done; label.append(box, " ", todo.text); const del = document.createElement("button"); del.className = "delete"; del.textContent = "Delete"; del.setAttribute("aria-label", `Delete ${todo.text}`); li.append(label, del); return li; } function render() { list.replaceChildren(...todos.filter(FILTERS[filter]).map(renderItem)); const left = todos.filter((t) => !t.done).length; document.getElementById("count").textContent = `${left} ${left === 1 ? "task" : "tasks"} left`; for (const button of document.querySelectorAll("#filters button")) { button.setAttribute("aria-pressed", String(button.dataset.filter === filter)); } } form.addEventListener("submit", (event) => { event.preventDefault(); const text = form.elements.text.value.trim(); if (!text) return; todos.push({ id: newId(), text, done: false }); form.reset(); render(); }); list.addEventListener("change", (event) => { const id = event.target.closest("li").dataset.id; todos.find((t) => t.id === id).done = event.target.checked; render(); }); list.addEventListener("click", (event) => { if (!event.target.closest(".delete")) return; const id = event.target.closest("li").dataset.id; todos = todos.filter((t) => t.id !== id); render(); }); document.getElementById("filters").addEventListener("click", (event) => { const button = event.target.closest("button"); if (!button) return; filter = button.dataset.filter; render(); }); document.getElementById("clear").addEventListener("click", () => { todos = todos.filter((t) => !t.done); render(); }); render();</script>

Preview

Switch to Active and tick a task: it disappears from the view, because it no longer matches the filter, but the counter updates and it is still there under All. Try adding a fourth filter, say long, for tasks with more than 15 characters: one entry in FILTERS and one button, and nothing else changes.

Two small details are doing real work. The filter buttons use aria-pressed, so assistive technology announces which one is on, and the CSS styles that same attribute instead of a separate class. And the counter has aria-live="polite", so screen readers announce "2 tasks left" when it changes.

Stage 4: save to localStorage

The last feature: tasks should survive a reload. localStorage stores strings under string keys, per website, with no expiry. Saving an array means turning it into a string with JSON.stringify, and loading means JSON.parse.

Storage can fail, though. The user may have blocked it, the browser may be in a strict private mode, or the storage quota may be full, and any of those throws an error. A good app catches that and carries on without saving. The previews on this site are a real example: they run in a locked-down frame where storage is switched off, so this stage will tell you saving is unavailable here. Copy the code into an index.html file on your computer, open it in a browser, and reloads will keep your tasks.

HTML & CSS
<style> body { max-width: 420px; } form, .filters { display: flex; gap: 8px; } input[type="text"] { flex: 1; font: inherit; padding: 6px 8px; } button { font: inherit; padding: 6px 12px; } ul { list-style: none; padding: 0; } li { display: flex; align-items: center; gap: 8px; padding: 6px 4px; border-bottom: 1px solid #e5e5e5; } li label { flex: 1; } li.done label { text-decoration: line-through; color: #777; } .delete { padding: 2px 8px; font-size: 13px; } .filters button[aria-pressed="true"] { background: #111; color: white; } footer { display: flex; justify-content: space-between; align-items: center; margin-top: 8px; } #storage-note { font-size: 13px; color: #666; }</style> <h2>To do</h2><form id="new-todo"> <label for="todo-text" hidden>New task</label> <input id="todo-text" type="text" name="text" placeholder="What needs doing?" required autocomplete="off"> <button>Add</button></form><div class="filters" id="filters"> <button data-filter="all">All</button> <button data-filter="active">Active</button> <button data-filter="done">Done</button></div><ul id="list"></ul><footer> <span id="count" aria-live="polite"></span> <button id="clear">Clear done</button></footer><p id="storage-note"></p> <script> const STORAGE_KEY = "razorcode-todos"; const note = document.getElementById("storage-note"); function load() { let raw; try { raw = localStorage.getItem(STORAGE_KEY); note.textContent = "Tasks are saved in this browser."; } catch { note.textContent = "Saving is unavailable here, so tasks will not survive a reload."; return []; } try { const saved = JSON.parse(raw); return Array.isArray(saved) ? saved : []; } catch { return []; // the saved text was not valid JSON, so start fresh } } function save() { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(todos)); } catch { // storage is blocked or full: keep working without saving } } let todos = load(); let filter = "all"; // A short random id, like "lq3x9k2f": time plus a few random characters function newId() { return Date.now().toString(36) + Math.random().toString(36).slice(2, 6); } const form = document.getElementById("new-todo"); const list = document.getElementById("list"); const FILTERS = { all: () => true, active: (todo) => !todo.done, done: (todo) => todo.done, }; function renderItem(todo) { const li = document.createElement("li"); li.dataset.id = todo.id; li.classList.toggle("done", todo.done); const label = document.createElement("label"); const box = document.createElement("input"); box.type = "checkbox"; box.checked = todo.done; label.append(box, " ", todo.text); const del = document.createElement("button"); del.className = "delete"; del.textContent = "Delete"; del.setAttribute("aria-label", `Delete ${todo.text}`); li.append(label, del); return li; } function render() { list.replaceChildren(...todos.filter(FILTERS[filter]).map(renderItem)); const left = todos.filter((t) => !t.done).length; document.getElementById("count").textContent = `${left} ${left === 1 ? "task" : "tasks"} left`; for (const button of document.querySelectorAll("#filters button")) { button.setAttribute("aria-pressed", String(button.dataset.filter === filter)); } } // Every change to the todos goes through here: change, save, render. function update(nextTodos) { todos = nextTodos; save(); render(); } form.addEventListener("submit", (event) => { event.preventDefault(); const text = form.elements.text.value.trim(); if (!text) return; update([...todos, { id: newId(), text, done: false }]); form.reset(); }); list.addEventListener("change", (event) => { const id = event.target.closest("li").dataset.id; update(todos.map((t) => (t.id === id ? { ...t, done: event.target.checked } : t))); }); list.addEventListener("click", (event) => { if (!event.target.closest(".delete")) return; const id = event.target.closest("li").dataset.id; update(todos.filter((t) => t.id !== id)); }); document.getElementById("filters").addEventListener("click", (event) => { const button = event.target.closest("button"); if (!button) return; filter = button.dataset.filter; render(); // the filter is view state, so it is not saved }); document.getElementById("clear").addEventListener("click", () => { update(todos.filter((t) => !t.done)); }); render();</script>

Preview

Two changes from stage 3 are worth a close look. First, every change to the tasks now goes through one update function, so saving can never be forgotten. Second, handlers no longer edit the array in place; they build a new array with map, filter and spread, and hand it to update. That habit, called immutable updates, is exactly how React expects you to change state.

Also notice what load guards against: localStorage.getItem returns null the first time (and JSON.parse(null) is null), and a hand-edited or corrupted value could be anything, even text that is not valid JSON at all. So load reads and parses in two separate try blocks (storage being blocked and bad data are different problems) and checks Array.isArray before trusting the result. Data coming in from outside your program deserves that care. Never store secrets like passwords or tokens in localStorage: any script running on the page can read it.

Predict the outputJavaScript

What does this print?

const saved = JSON.stringify([{ text: "Milk", done: false }]);
console.log(typeof saved);
Need a nudge? Hints walk you through it.
Quick check
You save with localStorage.setItem('todos', todos) without JSON.stringify. What ends up stored for an array of two task objects?
Need a nudge? A hint rules out a wrong answer.

What a framework would take off your hands

You now have a real app in about 100 lines of JavaScript, and a good design: state in one place, one render function, delegated events, immutable updates. It also has some rough edges that grow with the app:

  • Rebuilding everything on each render. Simple and correct, but it throws away DOM nodes the user might be using. Tick a checkbox with the keyboard and focus is lost, because that checkbox no longer exists. Fixing it by hand means comparing old and new lists and patching only what changed, which is fiddly code.
  • Building elements by hand. renderItem is twelve lines of createElement for a row you could describe in three lines of HTML.
  • Remembering to render. Forget render() (or update) in one handler and the page silently goes stale.
  • No components. As the app grows, there is no built-in way to split it into reusable pieces with their own state.

React solves exactly these. You describe what the UI should look like for a given state, using JSX, a syntax that looks like HTML inside JavaScript. When state changes through setTodos, React re-runs your component and compares the new description with the old one, then updates only the DOM nodes that differ. The key prop does the job your data-id did, telling React which item is which, so focus and checkbox state are kept.

function TodoItem({ todo, onToggle, onDelete }) {
  return (
    <li className={todo.done ? "done" : ""}>
      <label>
        <input type="checkbox" checked={todo.done} onChange={() => onToggle(todo.id)} />
        {" "}{todo.text}
      </label>
      <button onClick={() => onDelete(todo.id)} aria-label={`Delete ${todo.text}`}>Delete</button>
    </li>
  );
}
 
// in the parent: todos.filter(FILTERS[filter]).map((todo) => <TodoItem key={todo.id} todo={todo} ... />)

Look how much carries straight over: the todos array as state, filter functions, map to build the list, immutable updates. React still needs the DOM, events and forms you just learned; it automates the busywork around them.

Match the pairs0/4 matched

Match each piece of your vanilla app to what React gives you instead.

Choose an item, then its match on the other side.
Key terms
state
The data your app is currently showing, kept in JavaScript. The page is drawn from it.
render function
A function that builds the UI from the current state, so the page always matches the data.
single source of truth
Keeping each piece of data in one place, so different parts of the app cannot disagree.
immutable update
Changing state by building a new array or object instead of editing the old one in place.
localStorage
Browser storage for strings under string keys, per website, kept after the tab closes.
key
In React, a stable id on each list item that tells React which item is which between renders.