Build a JavaScript Todo App: Beginner DOM Project

Build a complete JavaScript todo app from scratch. Learn DOM manipulation, event handling, localStorage persistence, filtering, editing, and drag-and-drop reordering.

JavaScriptbeginner
13 min read

Building a todo app is one of the best ways to practice DOM manipulation, event handling, and data persistence. This project brings together everything you have learned about creating elements, event listeners, event delegation, and form handling into a single working application. You will build the app step by step, starting simple and adding features like editing, filtering, localStorage, and drag-and-drop reordering.

Project Overview

The finished todo app will support:

FeatureWhat It Does
Add todosType text and press Enter or click a button
Mark completeToggle checkbox to strike through the todo
Delete todosRemove individual items
Edit todosDouble-click to rename
Filter viewShow all, active, or completed todos
Count displayShow how many items remain
Clear completedBulk delete finished items
Persist dataSave to localStorage so todos survive page refresh

Step 1: Set Up the HTML Structure

The app starts with a simple HTML shell. All dynamic content will be created with JavaScript:

htmlhtml
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Todo App</title>
  <style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body { font-family: system-ui, sans-serif; background: #f5f5f5; padding: 40px 20px; }
    .todo-app { max-width: 500px; margin: 0 auto; background: white; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
    .todo-header { padding: 20px; border-bottom: 1px solid #eee; }
    .todo-header h1 { font-size: 24px; color: #333; margin-bottom: 12px; }
    .todo-input-row { display: flex; gap: 8px; }
    .todo-input-row input { flex: 1; padding: 10px 12px; border: 2px solid #ddd; border-radius: 6px; font-size: 16px; }
    .todo-input-row input:focus { border-color: #4a90d9; outline: none; }
    .todo-input-row button { padding: 10px 20px; background: #4a90d9; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 16px; }
    .todo-list { list-style: none; }
    .todo-item { display: flex; align-items: center; padding: 12px 20px; border-bottom: 1px solid #eee; gap: 12px; }
    .todo-item.completed .todo-text { text-decoration: line-through; color: #999; }
    .todo-text { flex: 1; font-size: 16px; }
    .todo-edit { flex: 1; font-size: 16px; padding: 4px 8px; border: 2px solid #4a90d9; border-radius: 4px; }
    .delete-btn { background: none; border: none; color: #e74c3c; cursor: pointer; font-size: 18px; opacity: 0.5; }
    .delete-btn:hover { opacity: 1; }
    .todo-footer { display: flex; justify-content: space-between; align-items: center; padding: 12px 20px; font-size: 14px; color: #777; }
    .filters { display: flex; gap: 8px; }
    .filters button { background: none; border: 1px solid #ddd; padding: 4px 10px; border-radius: 4px; cursor: pointer; font-size: 13px; }
    .filters button.active { border-color: #4a90d9; color: #4a90d9; }
    .clear-completed { background: none; border: none; color: #e74c3c; cursor: pointer; font-size: 13px; }
    .empty-state { padding: 40px 20px; text-align: center; color: #999; }
  </style>
</head>
<body>
  <div class="todo-app" id="app">
    <div class="todo-header">
      <h1>Todo App</h1>
      <div class="todo-input-row">
        <input type="text" id="todo-input" placeholder="What needs to be done?" autofocus>
        <button id="add-btn">Add</button>
      </div>
    </div>
    <ul class="todo-list" id="todo-list"></ul>
    <div class="todo-footer" id="todo-footer" style="display: none;">
      <span id="todo-count"></span>
      <div class="filters">
        <button class="active" data-filter="all">All</button>
        <button data-filter="active">Active</button>
        <button data-filter="completed">Completed</button>
      </div>
      <button class="clear-completed" id="clear-completed">Clear completed</button>
    </div>
  </div>
  <script src="todo.js"></script>
</body>
</html>

Step 2: Create the Data Model

Every todo has an id, text, and completed status. The data model is a simple array of objects:

javascriptjavascript
// todo.js - Data model
let todos = [];
let currentFilter = "all";
 
function generateId() {
  return Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
}
 
function addTodo(text) {
  const todo = {
    id: generateId(),
    text: text.trim(),
    completed: false,
    createdAt: Date.now()
  };
  todos.unshift(todo); // Add to beginning
  saveTodos();
  render();
}
 
function deleteTodo(id) {
  todos = todos.filter(todo => todo.id !== id);
  saveTodos();
  render();
}
 
function toggleTodo(id) {
  const todo = todos.find(t => t.id === id);
  if (todo) {
    todo.completed = !todo.completed;
    saveTodos();
    render();
  }
}
 
function editTodo(id, newText) {
  const todo = todos.find(t => t.id === id);
  if (todo && newText.trim()) {
    todo.text = newText.trim();
    saveTodos();
    render();
  }
}
 
function clearCompleted() {
  todos = todos.filter(todo => !todo.completed);
  saveTodos();
  render();
}

Step 3: Render the Todo List

The render function creates DOM elements for each todo and updates the display:

javascriptjavascript
// DOM references
const todoInput = document.getElementById("todo-input");
const todoList = document.getElementById("todo-list");
const todoFooter = document.getElementById("todo-footer");
const todoCount = document.getElementById("todo-count");
 
function getFilteredTodos() {
  switch (currentFilter) {
    case "active":
      return todos.filter(t => !t.completed);
    case "completed":
      return todos.filter(t => t.completed);
    default:
      return todos;
  }
}
 
function render() {
  const filtered = getFilteredTodos();
 
  // Clear existing list
  todoList.innerHTML = "";
 
  if (todos.length === 0) {
    todoList.innerHTML = '<li class="empty-state">No todos yet. Add one above!</li>';
    todoFooter.style.display = "none";
    return;
  }
 
  todoFooter.style.display = "flex";
 
  if (filtered.length === 0) {
    todoList.innerHTML = '<li class="empty-state">No matching todos</li>';
  } else {
    filtered.forEach(todo => {
      const li = createTodoElement(todo);
      todoList.appendChild(li);
    });
  }
 
  // Update count
  const activeCount = todos.filter(t => !t.completed).length;
  todoCount.textContent = `${activeCount} item${activeCount !== 1 ? "s" : ""} left`;
 
  // Update clear completed button visibility
  const hasCompleted = todos.some(t => t.completed);
  document.getElementById("clear-completed").style.display = hasCompleted ? "inline" : "none";
 
  // Update filter buttons
  document.querySelectorAll(".filters button").forEach(btn => {
    btn.classList.toggle("active", btn.dataset.filter === currentFilter);
  });
}
 
function createTodoElement(todo) {
  const li = document.createElement("li");
  li.className = `todo-item${todo.completed ? " completed" : ""}`;
  li.dataset.id = todo.id;
 
  // Checkbox
  const checkbox = document.createElement("input");
  checkbox.type = "checkbox";
  checkbox.checked = todo.completed;
  checkbox.className = "todo-checkbox";
 
  // Text span
  const textSpan = document.createElement("span");
  textSpan.className = "todo-text";
  textSpan.textContent = todo.text;
 
  // Delete button
  const deleteBtn = document.createElement("button");
  deleteBtn.className = "delete-btn";
  deleteBtn.textContent = "\u00D7"; // multiplication sign
  deleteBtn.title = "Delete todo";
 
  li.appendChild(checkbox);
  li.appendChild(textSpan);
  li.appendChild(deleteBtn);
 
  return li;
}

Step 4: Add Event Handling

Use event delegation on the list container instead of attaching listeners to every item:

javascriptjavascript
// Add todo: button click and Enter key
document.getElementById("add-btn").addEventListener("click", () => {
  const text = todoInput.value.trim();
  if (text) {
    addTodo(text);
    todoInput.value = "";
    todoInput.focus();
  }
});
 
todoInput.addEventListener("keydown", (e) => {
  if (e.key === "Enter") {
    const text = todoInput.value.trim();
    if (text) {
      addTodo(text);
      todoInput.value = "";
    }
  }
});
 
// Event delegation for todo list actions
todoList.addEventListener("click", (e) => {
  const item = e.target.closest(".todo-item");
  if (!item) return;
 
  const id = item.dataset.id;
 
  // Checkbox click: toggle completed
  if (e.target.classList.contains("todo-checkbox")) {
    toggleTodo(id);
    return;
  }
 
  // Delete button click
  if (e.target.classList.contains("delete-btn")) {
    deleteTodo(id);
    return;
  }
});
 
// Double-click to edit
todoList.addEventListener("dblclick", (e) => {
  const textSpan = e.target.closest(".todo-text");
  if (!textSpan) return;
 
  const item = textSpan.closest(".todo-item");
  const id = item.dataset.id;
  const todo = todos.find(t => t.id === id);
  if (!todo) return;
 
  // Replace text span with input
  const editInput = document.createElement("input");
  editInput.type = "text";
  editInput.className = "todo-edit";
  editInput.value = todo.text;
 
  textSpan.replaceWith(editInput);
  editInput.focus();
  editInput.select();
 
  function finishEdit() {
    const newText = editInput.value.trim();
    if (newText && newText !== todo.text) {
      editTodo(id, newText);
    } else {
      render(); // Restore original
    }
  }
 
  editInput.addEventListener("blur", finishEdit);
  editInput.addEventListener("keydown", (e) => {
    if (e.key === "Enter") finishEdit();
    if (e.key === "Escape") render(); // Cancel edit
  });
});
 
// Filter buttons
document.querySelector(".filters").addEventListener("click", (e) => {
  const filterBtn = e.target.closest("[data-filter]");
  if (!filterBtn) return;
 
  currentFilter = filterBtn.dataset.filter;
  render();
});
 
// Clear completed
document.getElementById("clear-completed").addEventListener("click", clearCompleted);

Step 5: Add localStorage Persistence

Save todos so they survive page refreshes using localStorage:

javascriptjavascript
const STORAGE_KEY = "todo-app-data";
 
function saveTodos() {
  const data = JSON.stringify(todos);
  localStorage.setItem(STORAGE_KEY, data);
}
 
function loadTodos() {
  const data = localStorage.getItem(STORAGE_KEY);
  if (data) {
    try {
      todos = JSON.parse(data);
    } catch (err) {
      console.error("Failed to parse saved todos:", err);
      todos = [];
    }
  }
}
 
// Load on startup
loadTodos();
render();

How localStorage Works

MethodPurposeExample
setItem(key, value)Save a stringlocalStorage.setItem("name", "John")
getItem(key)Read a stringlocalStorage.getItem("name") returns "John"
removeItem(key)Delete a keylocalStorage.removeItem("name")
clear()Delete everythinglocalStorage.clear()

localStorage only stores strings. Use JSON.stringify() to save objects and arrays, and JSON.parse() to read them back.

Step 6: Add Keyboard Shortcuts

javascriptjavascript
document.addEventListener("keydown", (e) => {
  // Ctrl+A or Cmd+A: focus the input (when not already focused)
  if ((e.ctrlKey || e.metaKey) && e.key === "k") {
    e.preventDefault();
    todoInput.focus();
    todoInput.select();
  }
 
  // Escape: clear input and blur
  if (e.key === "Escape" && document.activeElement === todoInput) {
    todoInput.value = "";
    todoInput.blur();
  }
});

Step 7: Add Drag-and-Drop Reordering

Let users rearrange todos by dragging, using native HTML5 drag and drop:

javascriptjavascript
let draggedItem = null;
 
function enableDragAndDrop() {
  todoList.addEventListener("dragstart", (e) => {
    const item = e.target.closest(".todo-item");
    if (!item) return;
 
    draggedItem = item;
    item.style.opacity = "0.4";
    e.dataTransfer.effectAllowed = "move";
  });
 
  todoList.addEventListener("dragend", (e) => {
    const item = e.target.closest(".todo-item");
    if (item) item.style.opacity = "1";
    draggedItem = null;
 
    // Remove all drag-over styles
    todoList.querySelectorAll(".todo-item").forEach(i => {
      i.style.borderTop = "";
    });
  });
 
  todoList.addEventListener("dragover", (e) => {
    e.preventDefault(); // Required to allow drop
    e.dataTransfer.dropEffect = "move";
 
    const item = e.target.closest(".todo-item");
    if (!item || item === draggedItem) return;
 
    // Clear all borders, then add to current target
    todoList.querySelectorAll(".todo-item").forEach(i => {
      i.style.borderTop = "";
    });
    item.style.borderTop = "2px solid #4a90d9";
  });
 
  todoList.addEventListener("drop", (e) => {
    e.preventDefault();
 
    const dropTarget = e.target.closest(".todo-item");
    if (!dropTarget || !draggedItem || dropTarget === draggedItem) return;
 
    const draggedId = draggedItem.dataset.id;
    const targetId = dropTarget.dataset.id;
 
    // Reorder the data array
    const dragIndex = todos.findIndex(t => t.id === draggedId);
    const targetIndex = todos.findIndex(t => t.id === targetId);
 
    const [movedItem] = todos.splice(dragIndex, 1);
    todos.splice(targetIndex, 0, movedItem);
 
    saveTodos();
    render();
  });
}
 
// Update createTodoElement to make items draggable
function createTodoElement(todo) {
  const li = document.createElement("li");
  li.className = `todo-item${todo.completed ? " completed" : ""}`;
  li.dataset.id = todo.id;
  li.draggable = true; // Enable drag
 
  const checkbox = document.createElement("input");
  checkbox.type = "checkbox";
  checkbox.checked = todo.completed;
  checkbox.className = "todo-checkbox";
 
  const textSpan = document.createElement("span");
  textSpan.className = "todo-text";
  textSpan.textContent = todo.text;
 
  const deleteBtn = document.createElement("button");
  deleteBtn.className = "delete-btn";
  deleteBtn.textContent = "\u00D7";
  deleteBtn.title = "Delete todo";
 
  li.appendChild(checkbox);
  li.appendChild(textSpan);
  li.appendChild(deleteBtn);
 
  return li;
}
 
enableDragAndDrop();

The Complete todo.js File

Here is the full JavaScript file with all features combined:

javascriptjavascript
// State
let todos = [];
let currentFilter = "all";
const STORAGE_KEY = "todo-app-data";
let draggedItem = null;
 
// DOM references
const todoInput = document.getElementById("todo-input");
const addBtn = document.getElementById("add-btn");
const todoList = document.getElementById("todo-list");
const todoFooter = document.getElementById("todo-footer");
const todoCount = document.getElementById("todo-count");
const clearCompletedBtn = document.getElementById("clear-completed");
const filtersContainer = document.querySelector(".filters");
 
// Data functions
function generateId() {
  return Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
}
 
function addTodo(text) {
  todos.unshift({ id: generateId(), text: text.trim(), completed: false, createdAt: Date.now() });
  saveTodos();
  render();
}
 
function deleteTodo(id) {
  todos = todos.filter(t => t.id !== id);
  saveTodos();
  render();
}
 
function toggleTodo(id) {
  const todo = todos.find(t => t.id === id);
  if (todo) { todo.completed = !todo.completed; saveTodos(); render(); }
}
 
function editTodo(id, newText) {
  const todo = todos.find(t => t.id === id);
  if (todo && newText.trim()) { todo.text = newText.trim(); saveTodos(); render(); }
}
 
function clearCompleted() {
  todos = todos.filter(t => !t.completed);
  saveTodos();
  render();
}
 
// Persistence
function saveTodos() { localStorage.setItem(STORAGE_KEY, JSON.stringify(todos)); }
 
function loadTodos() {
  const data = localStorage.getItem(STORAGE_KEY);
  if (data) { try { todos = JSON.parse(data); } catch { todos = []; } }
}
 
// Rendering
function getFilteredTodos() {
  if (currentFilter === "active") return todos.filter(t => !t.completed);
  if (currentFilter === "completed") return todos.filter(t => t.completed);
  return todos;
}
 
function createTodoElement(todo) {
  const li = document.createElement("li");
  li.className = `todo-item${todo.completed ? " completed" : ""}`;
  li.dataset.id = todo.id;
  li.draggable = true;
 
  const checkbox = document.createElement("input");
  checkbox.type = "checkbox";
  checkbox.checked = todo.completed;
  checkbox.className = "todo-checkbox";
 
  const textSpan = document.createElement("span");
  textSpan.className = "todo-text";
  textSpan.textContent = todo.text;
 
  const deleteBtn = document.createElement("button");
  deleteBtn.className = "delete-btn";
  deleteBtn.textContent = "\u00D7";
  deleteBtn.title = "Delete todo";
 
  li.appendChild(checkbox);
  li.appendChild(textSpan);
  li.appendChild(deleteBtn);
  return li;
}
 
function render() {
  const filtered = getFilteredTodos();
  todoList.innerHTML = "";
 
  if (todos.length === 0) {
    todoList.innerHTML = '<li class="empty-state">No todos yet. Add one above!</li>';
    todoFooter.style.display = "none";
    return;
  }
 
  todoFooter.style.display = "flex";
  if (filtered.length === 0) {
    todoList.innerHTML = '<li class="empty-state">No matching todos</li>';
  } else {
    filtered.forEach(todo => todoList.appendChild(createTodoElement(todo)));
  }
 
  const activeCount = todos.filter(t => !t.completed).length;
  todoCount.textContent = `${activeCount} item${activeCount !== 1 ? "s" : ""} left`;
  clearCompletedBtn.style.display = todos.some(t => t.completed) ? "inline" : "none";
  filtersContainer.querySelectorAll("button").forEach(btn => {
    btn.classList.toggle("active", btn.dataset.filter === currentFilter);
  });
}
 
// Event handlers
addBtn.addEventListener("click", () => {
  if (todoInput.value.trim()) { addTodo(todoInput.value); todoInput.value = ""; todoInput.focus(); }
});
 
todoInput.addEventListener("keydown", (e) => {
  if (e.key === "Enter" && todoInput.value.trim()) { addTodo(todoInput.value); todoInput.value = ""; }
});
 
todoList.addEventListener("click", (e) => {
  const item = e.target.closest(".todo-item");
  if (!item) return;
  if (e.target.classList.contains("todo-checkbox")) toggleTodo(item.dataset.id);
  if (e.target.classList.contains("delete-btn")) deleteTodo(item.dataset.id);
});
 
todoList.addEventListener("dblclick", (e) => {
  const textSpan = e.target.closest(".todo-text");
  if (!textSpan) return;
  const item = textSpan.closest(".todo-item");
  const todo = todos.find(t => t.id === item.dataset.id);
  if (!todo) return;
 
  const editInput = document.createElement("input");
  editInput.type = "text";
  editInput.className = "todo-edit";
  editInput.value = todo.text;
  textSpan.replaceWith(editInput);
  editInput.focus();
  editInput.select();
 
  function finishEdit() { const v = editInput.value.trim(); if (v && v !== todo.text) editTodo(todo.id, v); else render(); }
  editInput.addEventListener("blur", finishEdit);
  editInput.addEventListener("keydown", (e) => { if (e.key === "Enter") finishEdit(); if (e.key === "Escape") render(); });
});
 
filtersContainer.addEventListener("click", (e) => {
  const btn = e.target.closest("[data-filter]");
  if (btn) { currentFilter = btn.dataset.filter; render(); }
});
 
clearCompletedBtn.addEventListener("click", clearCompleted);
 
// Drag and drop
todoList.addEventListener("dragstart", (e) => {
  const item = e.target.closest(".todo-item");
  if (item) { draggedItem = item; item.style.opacity = "0.4"; e.dataTransfer.effectAllowed = "move"; }
});
 
todoList.addEventListener("dragend", (e) => {
  const item = e.target.closest(".todo-item");
  if (item) item.style.opacity = "1";
  draggedItem = null;
  todoList.querySelectorAll(".todo-item").forEach(i => i.style.borderTop = "");
});
 
todoList.addEventListener("dragover", (e) => {
  e.preventDefault();
  const item = e.target.closest(".todo-item");
  if (!item || item === draggedItem) return;
  todoList.querySelectorAll(".todo-item").forEach(i => i.style.borderTop = "");
  item.style.borderTop = "2px solid #4a90d9";
});
 
todoList.addEventListener("drop", (e) => {
  e.preventDefault();
  const target = e.target.closest(".todo-item");
  if (!target || !draggedItem || target === draggedItem) return;
  const di = todos.findIndex(t => t.id === draggedItem.dataset.id);
  const ti = todos.findIndex(t => t.id === target.dataset.id);
  const [moved] = todos.splice(di, 1);
  todos.splice(ti, 0, moved);
  saveTodos();
  render();
});
 
// Keyboard shortcut
document.addEventListener("keydown", (e) => {
  if ((e.ctrlKey || e.metaKey) && e.key === "k") { e.preventDefault(); todoInput.focus(); todoInput.select(); }
  if (e.key === "Escape" && document.activeElement === todoInput) { todoInput.value = ""; todoInput.blur(); }
});
 
// Initialize
loadTodos();
render();

Concepts Used in This Project

ConceptWhere UsedRelated Topic
createElementBuilding todo itemsDOM creation
appendChildAdding items to listDOM insertion
Event delegationList click/dblclick handlersEvent patterns
Event listenersAll interactionsDOM events
Click eventsButtons, checkboxes, filtersUser input
Keyboard eventsEnter to add, Escape to cancelKeyboard handling
querySelectorFinding DOM elementsDOM selection
Array methodsfilter, find, findIndex, someData manipulation
JSON methodslocalStorage serializationData persistence
Template literalsCount display textString building

Extending the Project

Ideas for adding more features to practice additional concepts:

Priority Levels

javascriptjavascript
function addTodo(text, priority = "normal") {
  todos.unshift({
    id: generateId(),
    text: text.trim(),
    completed: false,
    priority, // "low", "normal", "high"
    createdAt: Date.now()
  });
  saveTodos();
  render();
}
 
// Add priority indicator in createTodoElement
const priorityDot = document.createElement("span");
priorityDot.className = `priority-dot priority-${todo.priority}`;
li.insertBefore(priorityDot, checkbox);

Due Dates

javascriptjavascript
function addTodo(text, dueDate = null) {
  todos.unshift({
    id: generateId(),
    text: text.trim(),
    completed: false,
    dueDate, // ISO date string or null
    createdAt: Date.now()
  });
  saveTodos();
  render();
}
 
function isOverdue(todo) {
  if (!todo.dueDate || todo.completed) return false;
  return new Date(todo.dueDate) < new Date();
}

Categories or Tags

javascriptjavascript
function addTodo(text, tags = []) {
  todos.unshift({
    id: generateId(),
    text: text.trim(),
    completed: false,
    tags,
    createdAt: Date.now()
  });
  saveTodos();
  render();
}
 
// Filter by tag
function getTodosByTag(tag) {
  return todos.filter(t => t.tags.includes(tag));
}
Rune AI

Rune AI

Key Insights

  • Data drives the DOM: Keep todos in an array, and re-render the entire list from that array whenever data changes
  • Event delegation handles dynamic content: One listener on the parent list handles clicks for all current and future todo items
  • localStorage persists state: Stringify to save, parse to load, and always wrap JSON.parse in try/catch for safety
  • Render function is the single source of truth: Every change goes through addTodo/deleteTodo/toggleTodo, which call saveTodos and render
  • Progressive enhancement: Start with core features (add, toggle, delete) then layer on editing, filtering, drag-and-drop, and keyboard shortcuts
RunePowered by Rune AI

Frequently Asked Questions

Why use event delegation instead of adding listeners to each todo item?

[Event delegation](/tutorials/programming-languages/javascript/javascript-event-delegation-complete-tutorial) attaches one listener to the parent list instead of one per item. Since todos are added and removed dynamically, delegation means new items automatically respond to [click events](/tutorials/programming-languages/javascript/handling-click-events-in-javascript-full-guide) without you attaching new listeners. It also uses less memory because there is only one listener instead of many.

Why does the app use unshift instead of push to add todos?

`unshift` adds the new todo to the beginning of the array, so the most recent item appears at the top of the list. This matches the user expectation that new items are immediately visible without scrolling. You can use [push](/tutorials/programming-languages/javascript/js-array-push-and-pop-methods-a-complete-guide) instead if you prefer newest at the bottom.

How does localStorage persist data between page reloads?

`localStorage` stores key-value pairs as strings in the browser. When you call `localStorage.setItem("key", JSON.stringify(data))`, the browser writes it to disk. On page load, `localStorage.getItem("key")` retrieves the string, and `JSON.parse()` converts it back to a JavaScript [object or array](/tutorials/programming-languages/javascript/javascript-objects-arrays-complete-tutorial). The data persists until the user clears browser data or your code calls `removeItem` or `clear`.

Why use JSON.stringify and JSON.parse with localStorage?

localStorage only stores strings. If you save an object directly, it becomes `"[object Object]"`. `JSON.stringify()` converts the todos array to a JSON string like `[{"id":"abc","text":"Buy milk","completed":false}]`. `JSON.parse()` converts that string back to a real JavaScript array with objects you can use with [array methods](/tutorials/programming-languages/javascript/javascript-array-filter-method-complete-tutorial) like filter and find.

How can I add animations when adding or removing todos?

Use CSS transitions with JavaScript. When [adding an element](/tutorials/programming-languages/javascript/appending-elements-to-the-dom-in-js-full-guide), start with `opacity: 0` and `transform: translateY(-10px)`, then after a frame (using `requestAnimationFrame`), set `opacity: 1` and `transform: none`. When [removing elements](/tutorials/programming-languages/javascript/removing-html-elements-using-javascript-methods), add a CSS class with the exit animation, listen for the `transitionend` event, then remove the element from the DOM.

Conclusion

This todo app project combines DOM element creation, event delegation, form input handling, keyboard events, and localStorage persistence into one working application. The key patterns to remember are keeping a data model in sync with the DOM (render from data, not the other way around), using event delegation for dynamic lists, and saving state to localStorage on every change so nothing is lost on page refresh.