How to Build a Simple To-Do App in JavaScript (with localStorage)

A to-do app is the classic first JavaScript project because it teaches everything at once: DOM selection, events, rendering from state, and saving data. This tutorial builds one from scratch in plain JavaScript โ€” add, tick off, and delete tasks, with localStorage so nothing disappears on refresh โ€” and fixes the four mistakes beginners make most.

RH Raja HunainAuthor 01 Dec 2026 10 min read 9 views
Table of Contents
Share

Every JavaScript developer builds a to-do app sooner or later, and there is a good reason for that: it is the smallest project that still teaches the whole job. A to-do app forces you to read input, store data, draw the screen from that data, react to clicks, and save everything so it survives a page refresh. Those five skills show up in almost every web app you will ever build, from a shopping cart to a dashboard.

This tutorial builds a simple to-do app in JavaScript with plain HTML, CSS, and JavaScript โ€” no framework, no build step, no dependencies. By the end you will have an app where you can add a task, tick it off, delete it, and reload the page without losing anything, because tasks are saved in localStorage. Along the way you will learn the one pattern that keeps the code simple, and the four mistakes that make most beginner versions break.

The pattern: state, render, save

Before writing any code, understand the pattern, because it drives every decision below:

  1. State โ€” one array, tasks, holds every task as an object like { id: 1, text: "Buy milk", done: false }. This array is the single source of truth. Nothing else stores task data.
  2. Render โ€” one function, render(), draws the screen from the array. Whenever the state changes, you call render() and the screen is rebuilt to match.
  3. Save โ€” after every change, save() writes the array to localStorage. On page load, load() reads it back.

Every action in the app follows the same three steps: change the array, render, save. If you remember that recipe, the rest of the code writes itself.

Step 1: The HTML skeleton

Create a folder called todo-app and inside it three files: index.html, style.css, and app.js. Start with the HTML. It is deliberately minimal โ€” an input, an add button, and an empty list. JavaScript will fill the list.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My To-Do App</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <main class="app">
    <h1>My Tasks</h1>
    <p id="counter">0 tasks</p>

    <div class="add-row">
      <input id="taskInput" type="text" placeholder="Add a new task..." autocomplete="off">
      <button id="addBtn" type="button">Add</button>
    </div>

    <ul id="taskList"></ul>
  </main>

  <script src="app.js"></script>
</body>
</html>

Two details matter here. First, the <script> tag sits at the end of <body>, so the HTML above it already exists when app.js runs and getElementById can find the elements. Second, the list starts empty on purpose: the tasks live in JavaScript, and render() will build the <li> elements from the array.

Step 2: A little CSS

The styling is short โ€” just enough to make the app readable. The one rule worth noticing is .task.done .task-text, which crosses out a finished task. The JavaScript will add and remove the done class; the CSS decides what that looks like.

* { margin: 0; padding: 0; box-sizing: border-box; }

body {
  font-family: system-ui, sans-serif;
  background: #f4f4f5;
  color: #18181b;
  padding: 2rem 1rem;
}

.app { max-width: 480px; margin: 0 auto; }

h1 { font-size: 1.75rem; margin-bottom: 0.25rem; }
#counter { color: #71717a; margin-bottom: 1rem; }

.add-row { display: flex; gap: 0.5rem; margin-bottom: 1rem; }

#taskInput {
  flex: 1;
  padding: 0.6rem 0.75rem;
  border: 1px solid #d4d4d8;
  border-radius: 6px;
  font-size: 1rem;
}

#addBtn {
  padding: 0.6rem 1rem;
  border: none;
  border-radius: 6px;
  background: #2563eb;
  color: #fff;
  font-size: 1rem;
  cursor: pointer;
}

.task {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.6rem 0.75rem;
  background: #fff;
  border: 1px solid #e4e4e7;
  border-radius: 6px;
  margin-bottom: 0.5rem;
}

.task-text { flex: 1; cursor: pointer; }
.task.done .task-text { text-decoration: line-through; color: #a1a1aa; }

.delete-btn {
  border: none;
  background: none;
  color: #dc2626;
  font-size: 1.1rem;
  cursor: pointer;
}

Step 3: State, render, and the first task

Now the JavaScript. Open app.js and start with the state, the DOM references, and the render() function:

// State: the single source of truth.
let tasks = [];

// Grab the DOM elements once, at the top.
const input = document.getElementById('taskInput');
const addBtn = document.getElementById('addBtn');
const list = document.getElementById('taskList');
const counter = document.getElementById('counter');

// Draw the screen from the state.
function render() {
  // Clear the list first, then rebuild it from the array.
  list.innerHTML = '';

  tasks.forEach((task) => {
    const li = document.createElement('li');
    li.className = 'task' + (task.done ? ' done' : '');
    li.dataset.id = task.id;

    const checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.checked = task.done;

    const span = document.createElement('span');
    span.className = 'task-text';
    span.textContent = task.text;

    const delBtn = document.createElement('button');
    delBtn.type = 'button';
    delBtn.className = 'delete-btn';
    delBtn.textContent = 'โœ•';

    li.append(checkbox, span, delBtn);
    list.appendChild(li);
  });

  const remaining = tasks.filter((t) => !t.done).length;
  counter.textContent = remaining + ' task' + (remaining === 1 ? '' : 's') + ' left';
}

Notice that render() never edits one list item in place. It wipes the list and rebuilds it from tasks every time. That sounds wasteful, but for a list this size it is instant, and it removes a whole class of bugs: the screen can never drift out of sync with the data, because the screen is always generated from the data.

Also notice textContent, not innerHTML, for the task text. That is deliberate, and the mistakes section below explains why.

Step 4: Adding a task

Adding a task is one function that follows the recipe: change the array, render, save.

function addTask() {
  const text = input.value.trim();
  if (!text) return; // Ignore empty input.

  tasks.push({
    id: Date.now(), // A unique id for this task.
    text: text,
    done: false
  });

  input.value = ''; // Clear the box for the next task.
  input.focus();
  save();
  render();
}

addBtn.addEventListener('click', addTask);

// Let the Enter key add a task too.
input.addEventListener('keydown', (event) => {
  if (event.key === 'Enter') addTask();
});

Each task gets id: Date.now(), the current time in milliseconds. Two tasks are almost never created in the same millisecond, so the id is unique enough for this app โ€” and a stable id matters, because the delete step below must find the right task even after other tasks are removed. Using the task's position in the array instead is one of the classic beginner bugs, covered below.

Step 5: Tick off and delete with event delegation

The tick and delete buttons are created inside render(), so they do not exist when the page first loads. Attaching a listener to each button every time you render works, but it is wasteful and easy to forget. The cleaner approach is event delegation: attach one listener to the list itself, and let clicks bubble up to it. The listener checks what was actually clicked.

list.addEventListener('click', (event) => {
  const li = event.target.closest('li');
  if (!li) return;

  const id = Number(li.dataset.id);
  const task = tasks.find((t) => t.id === id);
  if (!task) return;

  if (event.target.matches('input[type="checkbox"]')) {
    task.done = !task.done; // Flip done true/false.
  } else if (event.target.matches('.delete-btn')) {
    tasks = tasks.filter((t) => t.id !== id);
  } else if (event.target.matches('.task-text')) {
    task.done = !task.done; // Clicking the text toggles too.
  } else {
    return;
  }

  save();
  render();
});

This is the same recipe again: find the task by its stable id, change the array, save, render. closest('li') walks up from the clicked element to the list item that holds it, and dataset.id reads the id that render() stored on that item. Because the listener lives on the <ul>, it keeps working for items created later โ€” there is nothing to re-attach after each render.

If you are new to closest() and matches(), they are worth learning now: they are the two methods that make event delegation practical, and you will use them in every list, table, and menu you build.

Step 6: Save with localStorage so tasks survive a refresh

Without this step, every task vanishes the moment the page reloads โ€” the most common complaint about beginner to-do apps. localStorage is the browser's tiny key-value store: data you put there stays on the user's computer until your code removes it.

function save() {
  localStorage.setItem('tasks', JSON.stringify(tasks));
}

function load() {
  const stored = localStorage.getItem('tasks');
  if (stored) {
    tasks = JSON.parse(stored);
  }
}

// Load saved tasks, then draw the screen.
load();
render();

Why JSON.stringify and JSON.parse? Because localStorage only stores strings. If you save an array directly, JavaScript converts it to the string "[object Object],[object Object]" and your data is gone. JSON.stringify turns the array into a JSON string first, and JSON.parse turns it back into a real array on load. Forgetting this pair is the second most common beginner mistake with localStorage.

Call load() before the first render(), so the saved tasks are in the array before the screen is drawn. Add a task, reload the page, and it is still there.

Four mistakes beginners make (and how this app avoids them)

1. Tasks disappear on refresh. The app has no save step. Fix: call save() after every change and load() before the first render, exactly as above.

2. Deleting the wrong task. The code deletes by array index, but after one task is removed every index after it shifts by one, so the next delete hits the wrong item. Fix: give each task a stable id and delete with filter((t) => t.id !== id).

3. innerHTML with user input. Building list items with li.innerHTML = `<span>${task.text}</span>` looks convenient, but a task typed as <img src=x onerror=alert(1)> would run as code. That is a cross-site scripting (XSS) hole in a real app. Fix: build elements with createElement and set text with textContent, which treats the input as plain text.

4. Editing the DOM instead of the state. When the code updates a list item directly and forgets to update the array, the screen and the data disagree โ€” and the next render() or save() overwrites the screen change or saves the wrong data. Fix: never touch the DOM to change a task. Change the array, then call render().

The complete app.js

Here is the whole file in one place. Save it as app.js, open index.html in a browser, and it works.

let tasks = [];

const input = document.getElementById('taskInput');
const addBtn = document.getElementById('addBtn');
const list = document.getElementById('taskList');
const counter = document.getElementById('counter');

function save() {
  localStorage.setItem('tasks', JSON.stringify(tasks));
}

function load() {
  const stored = localStorage.getItem('tasks');
  if (stored) {
    tasks = JSON.parse(stored);
  }
}

function render() {
  list.innerHTML = '';

  tasks.forEach((task) => {
    const li = document.createElement('li');
    li.className = 'task' + (task.done ? ' done' : '');
    li.dataset.id = task.id;

    const checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.checked = task.done;

    const span = document.createElement('span');
    span.className = 'task-text';
    span.textContent = task.text;

    const delBtn = document.createElement('button');
    delBtn.type = 'button';
    delBtn.className = 'delete-btn';
    delBtn.textContent = 'โœ•';

    li.append(checkbox, span, delBtn);
    list.appendChild(li);
  });

  const remaining = tasks.filter((t) => !t.done).length;
  counter.textContent = remaining + ' task' + (remaining === 1 ? '' : 's') + ' left';
}

function addTask() {
  const text = input.value.trim();
  if (!text) return;

  tasks.push({ id: Date.now(), text: text, done: false });

  input.value = '';
  input.focus();
  save();
  render();
}

addBtn.addEventListener('click', addTask);

input.addEventListener('keydown', (event) => {
  if (event.key === 'Enter') addTask();
});

list.addEventListener('click', (event) => {
  const li = event.target.closest('li');
  if (!li) return;

  const id = Number(li.dataset.id);
  const task = tasks.find((t) => t.id === id);
  if (!task) return;

  if (event.target.matches('input[type="checkbox"]')) {
    task.done = !task.done;
  } else if (event.target.matches('.delete-btn')) {
    tasks = tasks.filter((t) => t.id !== id);
  } else if (event.target.matches('.task-text')) {
    task.done = !task.done;
  } else {
    return;
  }

  save();
  render();
});

load();
render();

What to build next

Once the basic app works, extend it with one feature at a time โ€” each one teaches something new:

  • Filters (All / Active / Completed): filter the array before rendering, and keep the same render() shape.
  • Edit a task: double-click the text to turn it into an input, save on Enter.
  • Due dates and sorting: add a due field to the task object and sort the array before rendering.
  • Fetch from an API: load starter tasks with the Fetch API instead of starting empty, and save them to localStorage on first load.
  • A search box: reuse the same render idea, and debounce the input so filtering only runs after the user pauses typing.

The pattern stays the same at every size: change the state, render from it, save it. Learn that recipe here, and it will carry you through far bigger apps than a to-do list.

Was this helpful? 0 likes Login to like & bookmark
RH

Written by

Raja Hunain

Full Stack Developer at Raja Dev Solutions โ€” writes about real development work, the errors he faced and exactly how he fixed them, plus practical Laravel, PHP, JavaScript and MySQL tutorials.

More about the author

Comments (0)

No comments yet. Be the first to comment.

Leave a comment

Comments are moderated and appear after approval.

Keep reading

Related Articles

Tutorial JavaScript 27 Nov 2026 ยท 8 min read

How to Debounce in JavaScript: Build a Search Input That Stops Firing on Every Keystroke

Type ten letters into a search box and your code fires ten API requests โ€” nine of them for queries nobody will ever see. This tutorial shows how to debounce in JavaScript from scratch: a reusable debounce function, a search input that waits for the user to pause, leading vs trailing calls, a cancel method, the three mistakes that silently break debounce, and a small React hook version.