Enhanced Todo List
What you'll build
A todo list app where you can add tasks, mark them complete, filter by status (all/active/completed), and the list persists across page reloads using localStorage.
Goals
- Add, toggle, and delete todo items
- Filter tasks by status (all, active, completed)
- Persist todos to localStorage
- Load saved todos on page load
Prerequisites
- Arrays and array methods (filter, map)
- Objects and destructuring
- DOM events and localStorage
Steps
- 1
Set up HTML and state
Create an input, Add button, filter buttons, a list container, and a script tag. Initialize todos from localStorage or an empty array.
Code<input id="input" placeholder="Add task"> <button id="add">Add</button> <button data-filter="all">All</button> <button data-filter="active">Active</button> <button data-filter="done">Done</button> <ul id="list"></ul> <script> let todos = JSON.parse(localStorage.getItem("todos") || "[]"); let filter = "all"; </script>Expected result
Input, buttons, and empty list appear. Saved todos load if present.
- 2
Write the render function
Write render() that filters todos by the current filter, builds the list HTML, and saves to localStorage on every call.
Codeconst listEl = document.getElementById("list"); function save() { localStorage.setItem("todos", JSON.stringify(todos)); } function render() { const shown = todos.filter(t => filter === "all" ? true : filter === "active" ? !t.done : t.done ); listEl.innerHTML = shown.map(t => `<li><input type="checkbox" data-id="${t.id}" ${t.done ? "checked" : ""}>` + `<span>${t.title}</span>` + `<button data-del="${t.id}">x</button></li>` ).join(""); save(); }Expected result
The list renders based on the current filter, and state is saved.
- 3
Wire add, toggle, delete, and filter
Add listeners for the Add button, list clicks (toggle/delete via delegation), and filter buttons. Each action updates state and calls render().
Codedocument.getElementById("add").addEventListener("click", () => { const title = document.getElementById("input").value.trim(); if (!title) return; todos.push({ id: Date.now(), title, done: false }); document.getElementById("input").value = ""; render(); }); listEl.addEventListener("click", (e) => { const id = Number(e.target.dataset.id || e.target.dataset.del); if (e.target.dataset.del) todos = todos.filter(t => t.id !== id); else if (e.target.type === "checkbox") { const t = todos.find(t => t.id === id); if (t) t.done = e.target.checked; } render(); }); document.querySelectorAll("[data-filter]").forEach(btn => btn.addEventListener("click", () => { filter = btn.dataset.filter; render(); }) ); render();Expected result
Adding, toggling, deleting, and filtering all work, and todos persist on reload.
- 4
Add input validation & error handling
Add validation at user input points: check for empty values, non-numbers, negatives, and other anomalies, using try/catch or conditionals to show friendly messages. Robust JS programs don't crash on unexpected input.
Codefunction safeParse(value) { if (value === null || value === undefined || value === "") { throw new Error("Input is empty"); } const num = Number(value); if (Number.isNaN(num)) { throw new Error(`"${value}" is not a valid number`); } return num; } try { const n = safeParse(userInput); process(n); } catch (err) { console.error(err.message); }Expected result
Empty or non-number input shows an error message instead of crashing; valid numbers process normally.
- 5
Add event listeners & interaction
Bind event listeners (click, input, keydown, etc.) to page elements so the program responds to user actions. Interactivity is the core value of JavaScript in the front end.
Codeconst button = document.querySelector("#action-btn"); const input = document.querySelector("#user-input"); button.addEventListener("click", () => { const value = input.value.trim(); if (!value) return; runMainLogic(value); }); input.addEventListener("keydown", (e) => { if (e.key === "Enter") button.click(); });Expected result
Clicking the button or pressing Enter triggers the main logic; empty input is ignored.
Try it yourself
<input id="input" placeholder="Add task">
<button id="add">Add</button>
<!-- TODO: filter buttons + list -->
<script>
// TODO: load from localStorage, render, wire events
</script><input id="input" placeholder="Add task">
<button id="add">Add</button>
<button data-filter="all">All</button>
<button data-filter="active">Active</button>
<button data-filter="done">Done</button>
<ul id="list"></ul>
<script>
let todos = JSON.parse(localStorage.getItem("todos") || "[]");
let filter = "all";
const listEl = document.getElementById("list");
function save() { localStorage.setItem("todos", JSON.stringify(todos)); }
function render() {
const shown = todos.filter(t =>
filter === "all" ? true : filter === "active" ? !t.done : t.done
);
listEl.innerHTML = shown.map(t =>
`<li><input type="checkbox" data-id="${t.id}" ${t.done ? "checked" : ""}>` +
`<span>${t.title}</span>` +
`<button data-del="${t.id}">x</button></li>`
).join("");
save();
}
document.getElementById("add").addEventListener("click", () => {
const title = document.getElementById("input").value.trim();
if (!title) return;
todos.push({ id: Date.now(), title, done: false });
document.getElementById("input").value = "";
render();
});
listEl.addEventListener("click", (e) => {
const id = Number(e.target.dataset.id || e.target.dataset.del);
if (e.target.dataset.del) todos = todos.filter(t => t.id !== id);
else if (e.target.type === "checkbox") {
const t = todos.find(t => t.id === id);
if (t) t.done = e.target.checked;
}
render();
});
document.querySelectorAll("[data-filter]").forEach(btn =>
btn.addEventListener("click", () => { filter = btn.dataset.filter; render(); })
);
render();
</script>What you learned
You built a persistent todo app with filtering — combining array methods, event delegation, and localStorage to create a fully functional task manager that survives page reloads.
Related Resources
Related Practice
- Predict Array filter Output
Practice filtering arrays.
Related Cheatsheets
- JavaScript Cheatsheet
Array and DOM reference.
Related Glossary
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.