Explain it simply
Explain it simply
Compare a to-do list on paper with a to-do app on your phone. In the app, the real list is not the text on screen; it is an array in memory. The screen is just a snapshot of that array.
This project follows one simple rule: every change happens to the array (the state) first, and then the screen is redrawn from the state. You never patch the screen directly. That way the screen and the data can never drift apart, and after a page reload the app can start again from the state saved in localStorage.
Problem → Why → Solution
The problem: using the array index as an id
In the first version, the developer keeps the todos as an array of strings and puts the array index on each button as data-index. As soon as one item is deleted, every item after it moves up one position, but the buttons on screen have not been redrawn and still carry their old data-index values.
The user clicks delete on "Call Ana", and a different item disappears. Whether a task is done lives only as a CSS class in the DOM, so it vanishes on every page reload as well.
const todos = ["Buy milk", "Call Ana", "Write report"];
// buttons were rendered earlier with data-index="0", "1", "2"
list.addEventListener("click", (event) => {
const index = Number(event.target.dataset.index);
todos.splice(index, 1); // every later item shifts left
event.target.closest("li").remove();
// the remaining buttons still say 1 and 2, but the array is now 0 and 1
});
// "done" lives only in the DOM, so a reload forgets it
li.classList.add("done");Why does this happen?
An index is not an item's identity; it only says where the item sits right now, and that changes with every delete, sort or filter. When the data (the array) and the screen (the DOM) are edited separately, sooner or later they disagree. Give every todo a stable id that never changes and always redraw the screen from the state, and both problems go away.
Core concept: state is the truth, the UI is a picture of it
The app is split into three layers. The state logic: the state is one { nextId, items } object, and every item has an id, a title and a completed flag. The storage adapter, which turns the state into a string, saves it and reads it back. And the DOM renderer, which draws the HTML from the state. The first two layers know nothing about the DOM, so they can be tested in Node.
1. Hand out ids from the state
nextId lives in the state. Each new todo takes the current nextId and the counter moves up by one. Deleting an item never lowers it, so no id is ever reused. Apps that sync with a server often use a unique id such as crypto.randomUUID() instead.
2. Every change returns a new state
add builds a new array with spread, toggle uses map to copy only the item that changes, and delete removes one with filter. The old state is never edited.
3. A filter is only a view
Choosing "Active" or "Done" removes nothing from the state; visibleTodos() only computes the list to display. The distinction matters, because a filter that deleted items would lose data.
4. Do not trust data you load
The string in localStorage may have been edited by the user, a browser extension or an older version of your app. Wrap JSON.parse in try/catch, drop items with the wrong shape, and recompute nextId so it is always larger than the biggest existing id.
Is redrawing the whole list slow?
For lists of up to a few hundred todos, redrawing everything is faster than the eye can notice and keeps the code very simple. Only when you reach thousands of items is it worth updating just the changed rows, or reaching for a framework that does that for you.
- An event calls a state function
- The function returns a new state
- The new state is saved to storage
- The whole list is redrawn from state
Whenever you feel like editing something on screen directly, stop: change the state and call render() instead.
General pattern
const add = (state, data) => ({
nextId: state.nextId + 1,
items: [...state.items, { id: state.nextId, ...data }],
});
const update = (state, id, changes) => ({
...state,
items: state.items.map((it) => (it.id === id ? { ...it, ...changes } : it)),
});
const remove = (state, id) => ({
...state,
items: state.items.filter((it) => it.id !== id),
});Three shapes cover any state that manages a collection: add with spread into a new array, update with map that copies only the matching item, and remove with filter. Nothing is ever changed in place.
Run the todo logic and storage in Node
Node has no localStorage, so createMemoryStorage() builds an object with the same getItem and setItem methods on top of a Map. saveState and loadState take the storage as a parameter, so in the browser you simply pass localStorage instead. In the demo, watch how a blank title is ignored, how ids stay put after toggle and delete, and how corrupted data does not crash the app.
// todo-logic.js - state transitions only, no DOM
function createState() {
return { nextId: 1, items: [] };
}
function addTodo(state, text) {
const title = text.trim();
if (title === "") return state; // ignore empty input
const todo = { id: state.nextId, title, completed: false };
return { nextId: state.nextId + 1, items: [...state.items, todo] };
}
function toggleTodo(state, id) {
const items = state.items.map((t) =>
t.id === id ? { ...t, completed: !t.completed } : t,
);
return { ...state, items };
}
function deleteTodo(state, id) {
return { ...state, items: state.items.filter((t) => t.id !== id) };
}
function visibleTodos(items, filter) {
if (filter === "active") return items.filter((t) => !t.completed);
if (filter === "done") return items.filter((t) => t.completed);
return items; // "all"
}
function formatTodo(t) {
return `[${t.completed ? "x" : " "}] ${t.id}. ${t.title}`;
}
// Persistence: same getItem/setItem shape as the browser's localStorage
function createMemoryStorage() {
const data = new Map();
return {
getItem: (key) => (data.has(key) ? data.get(key) : null),
setItem: (key, value) => data.set(key, String(value)),
};
}
function saveState(storage, state) {
storage.setItem("todos", JSON.stringify(state));
}
function loadState(storage) {
try {
const saved = JSON.parse(storage.getItem("todos"));
if (!saved || !Array.isArray(saved.items)) return createState();
const items = saved.items.filter(
(t) => t && typeof t.id === "number" && typeof t.title === "string",
);
const maxId = items.reduce((max, t) => Math.max(max, t.id), 0);
return { nextId: Math.max(Number(saved.nextId) || 1, maxId + 1), items };
} catch {
return createState(); // corrupted JSON: start fresh instead of crashing
}
}
// Demo: every step replaces state with a new object
let state = createState();
state = addTodo(state, "Learn JavaScript");
state = addTodo(state, "Build a project");
state = addTodo(state, " "); // ignored: no id is used up
state = addTodo(state, "Master React");
state = toggleTodo(state, 1);
state = deleteTodo(state, 2);
console.log(state.items.map(formatTodo).join("\n"));
console.log("Active:", visibleTodos(state.items, "active").map((t) => t.title));
const storage = createMemoryStorage();
saveState(storage, state);
const reloaded = loadState(storage);
console.log("Reloaded:", reloaded.items.length, "items, next id", reloaded.nextId);
storage.setItem("todos", "{not json");
console.log("Corrupted:", loadState(storage).items.length, "items");Code breakdown
- Stable ids from the state
return { nextId: state.nextId + 1, items: [...state.items, todo] };The new todo takes the current nextId and the new state moves the counter up. A blank title returns early, before this line, so no id is used up and "Master React" gets 3.
- Copy only what changes
t.id === id ? { ...t, completed: !t.completed } : t,Only the item whose id matches is copied with completed flipped; every other item is reused as it is.
- Filter is a view
if (filter === "active") return items.filter((t) => !t.completed);It returns a new list for display and deletes nothing from the state, so switching back to "All" shows every item again.
- A storage adapter
setItem: (key, value) => data.set(key, String(value)),Like localStorage, it stores values as strings, which is why saveState() must call JSON.stringify() and loadState() must call JSON.parse().
- Validate what you load
(t) => t && typeof t.id === "number" && typeof t.title === "string",Items with the wrong shape are dropped, and nextId is recomputed to stay above the largest id. If the JSON itself is broken, the catch block starts from an empty state.
[x] 1. Learn JavaScript
[ ] 3. Master React
Active: [ 'Master React' ]
Reloaded: 2 items, next id 4
Corrupted: 0 itemsWiring the logic to the DOM
Once the logic file exports its functions, the browser side has only three jobs. render() redraws the <li> elements from the state, update() swaps in a new state, saves it and renders, and the listeners decide which function to call. A single click listener on the <ul> finds the todo from each <li>'s data-id, so new todos never need listeners of their own.
<form id="new-todo">
<input name="todo" placeholder="What needs doing?" autocomplete="off" />
<button>Add</button>
</form>
<ul id="list"></ul>
<script type="module">
import { addTodo, toggleTodo, deleteTodo, loadState, saveState }
from "./todo-logic.js";
let state = loadState(localStorage); // localStorage has getItem/setItem too
const list = document.querySelector("#list");
function render() {
list.replaceChildren(...state.items.map((todo) => {
const li = document.createElement("li");
li.dataset.id = todo.id;
li.textContent = todo.title; // textContent, never innerHTML
li.classList.toggle("done", todo.completed);
const del = document.createElement("button");
del.textContent = "Delete";
del.dataset.action = "delete";
li.append(del);
return li;
}));
}
function update(nextState) {
state = nextState;
saveState(localStorage, state);
render();
}
document.querySelector("#new-todo").addEventListener("submit", (event) => {
event.preventDefault();
const input = event.target.elements.todo;
update(addTodo(state, input.value));
input.value = "";
});
list.addEventListener("click", (event) => {
const li = event.target.closest("li");
if (!li) return;
const id = Number(li.dataset.id); // dataset values are strings
if (event.target.dataset.action === "delete") update(deleteTodo(state, id));
else update(toggleTodo(state, id));
});
render();
</script>Never put user text into innerHTML
With li.innerHTML = todo.title, a title such as <img src=x onerror=alert(1)> injects HTML and runs JavaScript in your page (XSS). Because it is saved in localStorage, it runs again on every reload. Always insert user data with textContent.
In real projects
In real projects
Drawing the UI from state is the foundation that React, Vue and Svelte are built on. Those frameworks make this lesson's render() efficient by updating only the elements that changed. React's rule that list items need key={todo.id} comes from the same stable-id problem: with the index as the key, deleting an item can leave typed text in the wrong row.
The storage adapter pays off as the app grows. You use localStorage today, but moving to a server API or IndexedDB later only means swapping what sits behind saveState and loadState; the state logic and the renderer stay untouched.
Production apps also store a version number with saved data and migrate old data when the shape changes. They write tests for the add, toggle, delete, filter and reload flows and run them in CI on every change.
Common mistakes
Common mistakes
Using the array index as the id
An index changes with every delete, sort and filter. With the "Active" filter on, index 1 on screen is not index 1 of the full list, so the wrong todo gets deleted or toggled. Use a stable id assigned when the item is created.
Comparing data-id as a string
li.dataset.id returns the string "3" while the id in the state is the number 3. t.id === "3" is false, so clicking toggle does nothing and no error appears. Convert with Number(li.dataset.id) before passing it on.
Editing state and DOM separately
Removing a todo from the array and separately calling li.remove() works until one code path forgets one half, and the screen and data disagree. Change only the state, then call render().
Trusting localStorage blindly
Writing JSON.parse(localStorage.getItem("todos")) without try/catch means one corrupted character stops the whole app from starting, and data saved by an older version as a bare array leaves items undefined. Guard the parse and check the shape.
Mini challenge
Add edit, clear completed and stats
Extend the todo logic with three features: editTodo to rename a todo, clearCompleted to remove finished todos, and stats to return the total, active and done counts. When there is nothing to change, return the very same state object.
- editTodo(state, id, newTitle) trims the title and returns the same state for a blank title or an unknown id
- editTodo never changes an item inside the old state
- clearCompleted(state) keeps only unfinished items and leaves nextId alone
- stats(items) returns { total, active, done }
// Reuse createState, addTodo and toggleTodo from the lesson (or compact versions).
function editTodo(state, id, newTitle) {
// TODO: trim newTitle; if it is blank or no item has this id, return state itself
// TODO: otherwise map over items and copy only the matching one with the new title
}
function clearCompleted(state) {
// TODO: keep unfinished items; nextId must not change
}
function stats(items) {
// TODO: return { total, active, done }
}
// TODO: add three todos, toggle one, then
// - rename todo 1 and show the old state still has the old title
// - show that a blank title and an unknown id both return the same object (===)
// - print stats before and after clearCompleted, plus the remaining idsExpected: Buy oat milk | original kept: Buy milk, blank edit ignored: true, unknown id ignored: true, then { total: 3, active: 2, done: 1 } before clearing, { total: 2, active: 2, done: 0 } after, and ids left: 1, 3 | next id: 4.
Show hint
Check for the id with state.items.some((t) => t.id === id). Test "same state" with editTodo(state, 1, " ") === state. Count done with filter(...).length; active is total - done.
Show solution
// Minimal core from the lesson, written compactly
const emptyState = () => ({ nextId: 1, items: [] });
const add = (state, text) => {
const title = text.trim();
if (!title) return state;
const item = { id: state.nextId, title, completed: false };
return { nextId: state.nextId + 1, items: [...state.items, item] };
};
const toggle = (state, id) => ({
...state,
items: state.items.map((t) =>
t.id === id ? { ...t, completed: !t.completed } : t,
),
});
// New features
function editTodo(state, id, newTitle) {
const title = newTitle.trim();
const exists = state.items.some((t) => t.id === id);
if (!title || !exists) return state; // nothing to change: same object back
return {
...state,
items: state.items.map((t) => (t.id === id ? { ...t, title } : t)),
};
}
function clearCompleted(state) {
return { ...state, items: state.items.filter((t) => !t.completed) };
}
function stats(items) {
const done = items.filter((t) => t.completed).length;
return { total: items.length, active: items.length - done, done };
}
// Build a list, then check each feature
let state = emptyState();
for (const text of ["Buy milk", "Write report", "Call Ana"]) state = add(state, text);
state = toggle(state, 2);
const before = state;
state = editTodo(state, 1, " Buy oat milk ");
console.log(state.items[0].title, "| original kept:", before.items[0].title);
console.log("blank edit ignored:", editTodo(state, 1, " ") === state);
console.log("unknown id ignored:", editTodo(state, 99, "Ghost") === state);
console.log("before clear:", stats(state.items));
state = clearCompleted(state);
console.log("after clear:", stats(state.items));
const ids = state.items.map((t) => t.id).join(", ");
console.log("ids left:", ids, "| next id:", state.nextId);Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- The state ({ nextId, items }) is the source of truth; always redraw the UI from it
- Give every todo a stable id that never changes; never use the array index
- Write add, toggle and delete as pure functions using spread, map and filter
- Hide storage behind an adapter and guard loaded data with try/catch and shape checks
- In the DOM, use event delegation, Number(dataset.id) and textContent
MDN — JavaScript Guide — MDN Web Docs