After this lesson you will have built a real, working to-do app that you wrote yourself: add tasks, tick them off, delete them, filter them and keep them after a reload. It uses nearly everything from the course: arrays and objects, filter, functions, the DOM, events, JSON and localStorage.
Read it with an editor open. Each step shows one piece of code and what it does, and the complete app is at the end, where you can run and edit it.
Plan before you code
A good first step is deciding what the app must do and what data it needs.
- Add a task from a text box. Refuse an empty one.
- Mark a task done and undo that.
- Delete a task.
- Show All, Active or Done tasks.
- Show how many tasks are left, and clear the finished ones.
- Remember everything after a reload.
Each task is one small object, for example { id: 2, text: "Build the to-do app", done: false }. The id is needed because we must identify a task even when the list is filtered. The whole list is an array of these objects. We call that array the state: the single place where the truth lives.
The key design idea is this loop, and it is why the app stays simple:
- Something happens (a click, a submit).
- The code changes the state array.
- The code saves the state.
- The code calls
render(), which redraws the page from the state.
We never edit one list item by hand. We change the data and redraw. This is the same idea that frameworks like React are built on, which you can see in the React course.
Step 1: the page structure
The HTML is a heading, a form, a message line, three filter buttons, an empty list and a footer. Nothing shows tasks yet; JavaScript fills the list.
<main class="app">
<h2>My tasks</h2>
<form id="add-form">
<input type="text" id="new-task" aria-label="New task" placeholder="What needs doing?" autocomplete="off">
<button type="submit">Add</button>
</form>
<p id="message" role="status"></p>
<div class="filters">
<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="list"></ul>
<div class="footer">
<span id="count"></span>
<button type="button" id="clear">Clear completed</button>
</div>
</main>Three small touches matter for real users. The input has an aria-label because it has no visible label. The message line has role="status" so a screen reader announces changes. And the filter buttons use aria-pressed so their state is not only shown by colour. Using a real <form> means that pressing Enter submits it for free.
Step 2: the state and render
Start with two variables and a function that turns the state into elements.
let tasks = [
{ id: 1, text: "Read the lesson", done: true },
{ id: 2, text: "Build the to-do app", done: false }
];
let filter = "all";
function render() {
const visible = tasks.filter(task =>
filter === "all" || (filter === "done" ? task.done : !task.done));
list.replaceChildren(...visible.map(task => {
const item = document.createElement("li");
item.dataset.id = task.id;
item.classList.toggle("done", task.done);
// ... checkbox, text and delete button go here
return item;
}));
}filter keeps only the tasks that match the current view. map turns each task into an <li> element, and replaceChildren swaps the old list contents for the new ones in one go. The data-id attribute stores the task's id on the element so that we can find the task again when it is clicked. Build elements with createElement as in Creating and removing elements, and set the task text with textContent, never innerHTML. If a user types <b>milk</b>, they then see exactly those characters, not bold text, and nobody can inject a script.
Step 3: adding tasks
Listen for the form's submit event. Stop the browser's default page reload, read and trim the text, and check it.
form.addEventListener("submit", event => {
event.preventDefault();
const text = input.value.trim();
if (text === "") {
message.textContent = "Please type a task first.";
return;
}
message.textContent = "";
tasks.push({ id: Date.now(), text, done: false });
input.value = "";
input.focus();
save();
render();
});Date.now() gives a number that is different for each task added at different moments, which is good enough for a personal list. Returning the focus to the box lets the user type the next task straight away. See Forms and validation for more on checking input.
Step 4: completing and deleting with one listener
You could add a click listener to each checkbox and each delete button inside render. A neater way is event delegation: one listener on the <ul> catches clicks bubbling up from anything inside, and checks what was clicked. See Event bubbling and delegation.
list.addEventListener("click", event => {
const id = Number(event.target.closest("li")?.dataset.id);
if (event.target.dataset.action === "delete") {
tasks = tasks.filter(task => task.id !== id);
} else if (event.target.type === "checkbox") {
const task = tasks.find(task => task.id === id);
task.done = event.target.checked;
} else {
return;
}
save();
render();
});closest("li") walks up from the clicked element to its list item, and ?. (from Optional chaining) keeps this safe if a click lands somewhere else. Notice the pattern: change tasks, then save(), then render(). Deleting uses filter to keep every task except the one with that id.
Step 5: filters, counter and clearing
Another delegated listener on the filter row sets the filter variable and redraws. The counter is computed from the state each time, and "Clear completed" keeps only the unfinished tasks:
const left = tasks.filter(task => !task.done).length;
count.textContent = left + (left === 1 ? " task left" : " tasks left");
document.getElementById("clear").addEventListener("click", () => {
tasks = tasks.filter(task => !task.done);
save();
render();
});The count uses the whole list, not just the visible tasks, so it stays the same when you switch filter. The ternary picks the singular or plural wording.
Step 6: remembering tasks
localStorage keeps text in the browser between visits. Arrays must be converted with JSON.stringify to save, and JSON.parse to load. Both can fail, so wrap them:
function save() {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
} catch (error) {
message.textContent = "Tasks could not be saved in this preview.";
}
}Loading uses the same idea: try to parse the saved text, and fall back to a starter list if storage is blocked or the text is damaged. The editor on this page runs your code in an isolated frame that cannot use storage, so there you will see the "could not be saved" message after changes. The app still works for as long as the page stays open. Copy the code into a file on your own computer, open it from a local server or a hosted page, and the tasks survive a reload. The HTML viewer tool is a handy place to paste and try it.
The complete app
This is the whole program. Open the editor, read it from top to bottom, then try the exercises that follow.
<style>
* { box-sizing: border-box; }
body { font-family: system-ui, sans-serif; margin: 0; padding: 12px; }
.app { max-width: 420px; margin: 0 auto; }
h2 { margin: 0 0 10px; }
form { display: flex; gap: 6px; }
input[type="text"] { flex: 1; padding: 8px; font: inherit; }
button { padding: 8px 10px; font: inherit; cursor: pointer; }
#message { min-height: 1.4em; margin: 6px 0; color: #b91c1c; font-size: 0.9rem; }
.filters { display: flex; gap: 6px; margin-bottom: 8px; }
.filters button[aria-pressed="true"] { background: #1e3a8a; color: #fff; }
ul { list-style: none; margin: 0; padding: 0; }
li { display: flex; align-items: center; gap: 8px; padding: 6px 0; border-bottom: 1px solid #ddd; }
li span { flex: 1; word-break: break-word; }
li.done span { text-decoration: line-through; color: #6b7280; }
.footer { display: flex; justify-content: space-between; align-items: center; margin-top: 10px; }
</style>
<main class="app">
<h2>My tasks</h2>
<form id="add-form">
<input type="text" id="new-task" aria-label="New task" placeholder="What needs doing?" autocomplete="off">
<button type="submit">Add</button>
</form>
<p id="message" role="status"></p>
<div class="filters">
<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="list"></ul>
<div class="footer">
<span id="count"></span>
<button type="button" id="clear">Clear completed</button>
</div>
</main>
<script>
const STORAGE_KEY = "task-app-demo";
const form = document.getElementById("add-form");
const input = document.getElementById("new-task");
const message = document.getElementById("message");
const list = document.getElementById("list");
const count = document.getElementById("count");
let tasks = load();
let filter = "all";
function load() {
try {
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY));
if (Array.isArray(saved)) return saved;
} catch (error) {
// storage blocked or the saved text is damaged: start empty
}
return [
{ id: 1, text: "Read the lesson", done: true },
{ id: 2, text: "Build the to-do app", done: false }
];
}
function save() {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
} catch (error) {
message.textContent = "Tasks could not be saved in this preview.";
}
}
function render() {
const visible = tasks.filter(task =>
filter === "all" || (filter === "done" ? task.done : !task.done));
list.replaceChildren(...visible.map(task => {
const item = document.createElement("li");
item.dataset.id = task.id;
item.classList.toggle("done", task.done);
const box = document.createElement("input");
box.type = "checkbox";
box.checked = task.done;
box.setAttribute("aria-label", "Done: " + task.text);
const label = document.createElement("span");
label.textContent = task.text;
const remove = document.createElement("button");
remove.type = "button";
remove.textContent = "Delete";
remove.dataset.action = "delete";
remove.setAttribute("aria-label", "Delete " + task.text);
item.append(box, label, remove);
return item;
}));
const left = tasks.filter(task => !task.done).length;
count.textContent = left + (left === 1 ? " task left" : " tasks left");
document.querySelectorAll("[data-filter]").forEach(button =>
button.setAttribute("aria-pressed", String(button.dataset.filter === filter)));
}
form.addEventListener("submit", event => {
event.preventDefault();
const text = input.value.trim();
if (text === "") {
message.textContent = "Please type a task first.";
return;
}
message.textContent = "";
tasks.push({ id: Date.now(), text, done: false });
input.value = "";
input.focus();
save();
render();
});
list.addEventListener("click", event => {
const id = Number(event.target.closest("li")?.dataset.id);
if (event.target.dataset.action === "delete") {
tasks = tasks.filter(task => task.id !== id);
} else if (event.target.type === "checkbox") {
const task = tasks.find(task => task.id === id);
task.done = event.target.checked;
} else {
return;
}
save();
render();
});
document.querySelector(".filters").addEventListener("click", event => {
if (!event.target.dataset.filter) return;
filter = event.target.dataset.filter;
render();
});
document.getElementById("clear").addEventListener("click", () => {
tasks = tasks.filter(task => !task.done);
save();
render();
});
render();
</script>Common mistakes
- Editing the page and forgetting the data. If you remove an
<li>but not the task from the array, it comes back on the next render. Change the state first, then render. - Forgetting
event.preventDefault()in the submit handler. The page reloads and your list disappears. - Comparing ids as the wrong type.
dataset.idis always a string, while the stored id is a number. That is why the code wraps it inNumber(...). - Using
innerHTMLfor user text. It lets typed markup run. UsetextContent. - Using
Date.now()ids in a loop. Two tasks created in the same millisecond would share an id. For a quick list it is fine, but for bulk creation use a counter. - Not handling blocked or damaged storage.
JSON.parse(null)returnsnulland bad text throws, so always load insidetryand check the result withArray.isArray. - Putting everything in one giant function. Small functions named
load,saveandrenderare far easier to debug (see Debugging with the browser tools).
Exercise
Extend the app yourself, one feature at a time, and run it after each change.
- Show a small line of text such as "Nothing here yet" when the visible list is empty.
- Stop duplicates: before adding, check whether
tasks.some(...)already has the same text, ignoring case, and show a message instead. - Let a user edit a task by double-clicking its text.
- Add a "Mark all done" button.
- Challenge: split the code into modules (see Modules: import and export), for example a
storage.jswithloadandsave.
That completes the JavaScript course. You can now build interactive pages, work with data, handle errors and talk to the internet. Good next steps are building something of your own, or following the React course to see how a framework organises this same idea of state and rendering.
Key points
- Keep your data in one array (the state) and write a render function that draws the page from it.
- After every change, update the state, save it, and call render again instead of editing the page by hand.
- One click listener on the list handles every checkbox and delete button through event delegation.
- Create elements with createElement and textContent, so typed text can never be treated as HTML.
- Wrap localStorage in try and catch, because it can be blocked, and always trim and check user input.
Check yourself
Free tools for this lesson
Final exam and certificate
Finish all 58 lessons to unlock a 15-question exam on JavaScript. Pass it and you get a certificate with a public link you can share.
Sign in to take the exam