DEV Community

Arhan Khan
Arhan Khan

Posted on

Build a Notes App with JavaScript

A notes app is the classic beginner project because it covers the full CRUD cycle: create, read, update, and delete. Add localStorage and your notes survive a refresh — suddenly it is not a demo anymore, it is a tool you can actually use.

What you are building

A text input to add a note, a list of notes, edit and delete buttons on each note, and a search box to filter them. Everything is saved in localStorage.

The data model

Keep one array as the source of truth. Every change updates the array, saves it, and re-renders:

let notes = JSON.parse(localStorage.getItem("notes") || "[]");

function saveNotes() {
  localStorage.setItem("notes", JSON.stringify(notes));
}

function addNote(text) {
  notes.unshift({
    id: Date.now(),
    text: text,
    created: new Date().toLocaleDateString(),
  });
  saveNotes();
  renderNotes();
}
Enter fullscreen mode Exit fullscreen mode

Rendering and deleting

Render from the array every time. Event delegation — one listener on the list instead of one per button — keeps the code short:

function renderNotes(filter = "") {
  const list = document.getElementById("notes-list");
  list.innerHTML = "";

  notes
    .filter((note) => note.text.toLowerCase().includes(filter.toLowerCase()))
    .forEach((note) => {
      const item = document.createElement("div");
      item.className = "note";
      item.innerHTML = `
        <p>${note.text}</p>
        <small>${note.created}</small>
        <button data-delete="${note.id}">Delete</button>
        <button data-edit="${note.id}">Edit</button>`;
      list.appendChild(item);
    });
}

document.getElementById("notes-list").addEventListener("click", (event) => {
  const deleteId = event.target.dataset.delete;
  const editId = event.target.dataset.edit;

  if (deleteId) {
    notes = notes.filter((note) => note.id !== Number(deleteId));
    saveNotes();
    renderNotes();
  }

  if (editId) {
    const note = notes.find((n) => n.id === Number(editId));
    const updated = prompt("Edit note:", note.text);
    if (updated !== null && updated.trim() !== "") {
      note.text = updated.trim();
      saveNotes();
      renderNotes();
    }
  }
});
Enter fullscreen mode Exit fullscreen mode

Why localStorage matters

Without persistence, every refresh wipes the app and the user stops trusting it. localStorage holds about 5 MB per site, stores strings only (hence JSON.stringify), and is synchronous — perfect for a notes app, but not for large data or anything sensitive.

What to add next

Add pinning, colour labels, a character count per note, or export all notes as a text file. Sorting by date and a dark mode are also good small wins.

Top comments (0)