TalentJR

🟨 JavaScript tutorial for beginners · Class 8 · Lesson 15 of 18 · Free

Building a To-Do List App – Arrays + DOM Together

⏱ About 40 minutes · ▶ run real JavaScript here — nothing to install · no sign-in

In this lesson you will

  • Keep tasks as an array of objects and change them with push, map and filter
  • Show the array on the page with a render() function
  • Add, tick, delete and save tasks with clicks and localStorage

Exams are next week. You have Maths sums, a Science project, and your bag to pack. A paper list gets lost, so let us build our own to-do app! It uses everything you learnt: arrays (Lesson 7), the DOM (Lesson 4), events (Lesson 5) and localStorage (Lesson 13).

How do I plan a to-do list app in JavaScript?

Every app has two parts: the **data** (what we know) and the **screen** (what we show). Good apps keep the data first and draw the screen from it.

Our data is an array. Each task is an object with `text` and `done` (true or false). You learnt objects in Lesson 10.

Before we touch the page, let us print the list in the console. ☐ means not done, ✅ means done.

🎬 How JavaScript thinks — step 1 of 12JavaScript is about to run line 1
▶const tasks = [
2 { text: "Maths sums", done: false },
3 { text: "Science project", done: true },
4 { text: "Pack school bag", done: false }
5];
6
7for (const task of tasks) {
8 const box = task.done ? "✅" : "☐";
9 console.log(box, task.text);
10}
11console.log("Tasks:", tasks.length);
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
☐ Maths sums
✅ Science project
☐ Pack school bag
Tasks: 3

💡 Try it: add a fourth task, like { text: "Water the plants", done: false }.

How do I add, tick and delete tasks in a JavaScript array?

Three jobs, three array tools. `push` adds a task at the end. Changing `done` ticks a task. `filter` (Lesson 8) keeps only the tasks we want, so it can delete one.

We delete by **position** (index): keep every task whose index is not the one to delete.

Watch the array change step by step in the animation.

🎬 How JavaScript thinks — step 1 of 8JavaScript is about to run line 1
▶let tasks = [{ text: "Maths sums", done: false }];
2
3// add
4tasks.push({ text: "Read Chapter 5", done: false });
5tasks.push({ text: "Pack bag", done: false });
6
7// tick task 0
8tasks[0].done = true;
9
10// delete task 1
11tasks = tasks.filter((task, i) => i !== 1);
12
13console.log(tasks);
14console.log("Left to do:", tasks.filter((t) => !t.done).length);
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
[{ text: "Maths sums", done: true }, { text: "Pack bag", done: false }]
Left to do: 1

How do I show an array as a list on the page?

Now we draw the screen from the data. A `render()` function empties the list, then makes one `<li>` for each task with `createElement`.

Why empty it first? If we did not, every render would add the tasks again, and you would see each task twice!

Whenever the data changes, we just call `render()` again. One function, always correct.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Drew 2 tasks

How do I add a task from an input box with JavaScript?

Read `input.value`, push a new object into the array, then `render()`. Afterwards, clear the box so the next task is easy to type.

We use `trim()` (Lesson 11) to remove spaces, and skip empty tasks. Nobody needs a blank task!

We use a form, so pressing **Enter** also works. `event.preventDefault()` stops the page from reloading (Lesson 12).

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Type a task and press Enter

💡 Try it: add three tasks. Then try adding only spaces — nothing happens.

How do I tick and delete tasks when they are clicked?

Each `<li>` gets its own click listener. Clicking the text flips `done`. Clicking ✖ removes the task with `splice(i, 1)`, which deletes 1 item at position i.

Look: the click handlers only change the **data**, then call `render()`. They never edit the `<li>` directly. That keeps the app simple and bug-free.

`event.stopPropagation()` stops the ✖ click from also counting as a click on the task.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Done: 0 of 2

How do I save my to-do list so it stays after reload?

Last step: memory! After every change we save the array with `JSON.stringify`. When the page starts, we load it with `JSON.parse`, just like Lesson 13.

`|| "[]"` means: if nothing is saved yet, start with an empty list.

Add a task, then press ▶ Run again. Your task is still there!

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Loaded 0 saved tasks

💡 The output here shows 0 saved tasks. On your screen it shows how many you saved. Try it: add a Clear all button that empties the array, saves and renders.

🤔 Predict the output

Think like JavaScript: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

const tasks = ["Maths", "Read"];
tasks.push("Pack bag");
console.log(tasks.length);

Question 2. What does this print?

const tasks = ["a", "b", "c"];
const left = tasks.filter((t, i) => i !== 1);
console.log(left);

Question 3. What does this print?

const tasks = [
  { text: "HW", done: true },
  { text: "Bag", done: false },
  { text: "Read", done: false }
];
console.log(tasks.filter((t) => !t.done).length);

🧩 Your challenge

Write the brain of a **Diwali shopping list**. Finish `addItem(text)`, `buyItem(index)` and `showList()`. `showList` prints each item with ☐ or ✅, then how many are left to buy. Expected output: ``` ☐ Diyas ✅ Rangoli colours ☐ Sweets ✅ Lanterns Left to buy: 2 ```

Expected output in the console:
☐ Diyas
✅ Rangoli colours
☐ Sweets
✅ Lanterns
Left to buy: 2
🟨 JavaScript — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

const tasks = ["Maths sums", "Pack bag"];
const list = document.querySelector("#list");
function render() {
  for (const t of tasks) {
    const li = document.createElement("li");
    li.textContent = t;
    list.appendChild(li);
  }
}
render();
render();
console.log("Items on page:", list.children.length);

No error, but every task shows twice (4 items on the page instead of 2).

✅ Right

const tasks = ["Maths sums", "Pack bag"];
const list = document.querySelector("#list");
function render() {
  list.innerHTML = "";
  for (const t of tasks) {
    const li = document.createElement("li");
    li.textContent = t;
    list.appendChild(li);
  }
}
render();
render();
console.log("Items on page:", list.children.length);

render() must empty the list first with list.innerHTML = "". Otherwise each render adds the tasks again.

❌ Wrong

const box = document.querySelector("#box");
const tasks = [];
tasks.push(box);
console.log("Saved task:", String(tasks[0]));

No error, but the task shows as [object HTMLInputElement] instead of the text you typed.

✅ Right

const box = document.querySelector("#box");
const tasks = [];
tasks.push(box.value);
console.log("Saved task:", String(tasks[0]));

box is the whole input element. The typed text is box.value.

❌ Wrong

const list = document.querySelector("taskList");
const li = document.createElement("li");
li.textContent = "Maths sums";
list.appendChild(li);

TypeError: Cannot read properties of null (reading 'appendChild')

✅ Right

const list = document.querySelector("#taskList");
const li = document.createElement("li");
li.textContent = "Maths sums";
list.appendChild(li);
console.log("Added:", li.textContent);

querySelector needs # for an id. Without it, it looks for a <taskList> tag, finds nothing, and gives null.

📌 Remember

  • Keep the data in an array of objects: { text, done }.
  • render() empties the list, then makes one <li> per task.
  • Click handlers change the data, then call render() again.
  • push adds, filter or splice deletes, task.done = !task.done ticks.
  • Save with JSON.stringify and load with JSON.parse to remember tasks.

Finished the quiz and the challenge?

Questions students ask

How do I make a to-do list in JavaScript?

Keep the tasks in an array. Write a render() function that shows the array as <li> items. When the user adds, ticks or deletes a task, change the array and call render() again.

Why do my to-do items appear twice?

Your render() function adds items without emptying the list first. Put list.innerHTML = "" at the start of render().

How do I keep my to-do list after refreshing the page?

Save the array with localStorage.setItem("todo", JSON.stringify(tasks)) after every change. When the page starts, load it with JSON.parse(localStorage.getItem("todo") || "[]").

Is a to-do list a good first JavaScript project?

Yes. It is small, but it uses arrays, objects, functions, events, the DOM and storage together. Once it works, you can add features like due dates or priorities.