JavaScript・Input and storage

Making the browser remember: localStorage

Browsers come with a notepad that survives closing the page. How to save, read, and delete values with localStorage, plus the "text only" catch and what must never go in it.

Values in variables vanish when the page reloads. Browsers come with a notepad that survives closing the page, and it’s called localStorage. It suits things worth remembering: a dark mode preference, a high score.

Three operations to learn

localStorage.setItem("name", "Shima");        // save
const name = localStorage.getItem("name");    // read
localStorage.removeItem("name");              // delete
Written asWhat it does
setItem("key", "value")Save under a label
getItem("key")Find by label and read
removeItem("key")Delete what’s under that label
clear()Delete everything this site saved

The "name" part is the key—a label, like an object’s key, that you choose yourself.

Check whether something was saved

When nothing was saved, getItem returns null, the “nothing here” marker. Checking after reading is the standard shape.

const saved = localStorage.getItem("name");

if (saved === null) {
  console.log("Nothing saved yet");
} else {
  console.log("Last time it was " + saved);
}

Run this when the page opens and you have a page that picks up where it left off.

Only text fits

localStorage holds text and nothing else. This is where people trip.

localStorage.setItem("score", 100);
const score = localStorage.getItem("score");
console.log(score + 1);   // "1001"

To use it as a number, convert after reading:

const score = Number(localStorage.getItem("score"));
console.log(score + 1);   // 101

For arrays and objects, turn them into text first:

const likes = ["drawing", "ramen"];

localStorage.setItem("likes", JSON.stringify(likes));      // to text, then save
const saved = JSON.parse(localStorage.getItem("likes"));   // back to the original

console.log(saved[0]);
  • JSON.stringify() — turns arrays and objects into text
  • JSON.parse() — turns text back into the original shape

They come as a pair: stringify on the way in, parse on the way out.

A typical use

// Remember the dark mode setting
localStorage.setItem("theme", "dark");

// Restore it next time the page opens
if (localStorage.getItem("theme") === "dark") {
  document.body.classList.add("dark");
}

That pattern alone gives you a page people don’t have to configure twice.

CSSLet's support dark modeBuilding the dark mode appearance itself, in the CSS course

Looking at what’s stored

Browser dev tools show you the contents. In Chrome: the Application tab → Local Storage in the left menu. Keys and values appear as a table, and you can delete entries right there.

Handy for confirming that a save you thought worked actually did.

TipsGetting started with developer toolsStart here if you’ve never opened the dev tools

What must never go in it

A few other traits worth knowing:

  • Per browser, per device. Chrome and Safari don’t share, and neither do your phone and your laptop
  • Per site. Other sites can’t read yours
  • Capacity is around 5MB. Plenty for text, wrong for stuffing images into
  • “Clear browsing data” wipes it all. Only store things you can afford to lose

Summary of this lesson

  1. setItem saves, getItem reads, removeItem deletes—and it survives closing the page
  2. Only text fits. Use Number() for numbers, JSON.stringify() and JSON.parse() for arrays and objects
  3. Anyone can read it, so never store passwords or personal data

Try it

The “localStorage” you learned today is not used on Shima’s page (there’s no setting worth remembering). It’s a tool for pages that recall a dark mode preference, or keep half-written content around. Keep it in mind and use it when you need it.

FAQ

When does data in localStorage disappear?
It stays until you remove it with removeItem or clear, or until the user clears their browsing data. Closing the page or restarting the computer doesn't touch it.
Can I store numbers or objects in localStorage?
Only text is stored. Convert numbers back with Number() after reading, and turn objects and arrays into text with JSON.stringify() before saving.
What's the difference between localStorage and sessionStorage?
sessionStorage is cleared when that tab closes. Use localStorage for things worth remembering long term, sessionStorage for temporary values.