Remembering Things with localStorage

Grade 12, page 7 of 9. A two-minute read.

Here's a problem. Build a page that lets the user choose dark mode. Now refresh the page. Their choice is gone! Every variable is wiped clean each time the page loads (remember the Professor's Corner in Grade 1?).

To remember things between visits, browsers give you localStorage: a little storage box for each website that survives refreshes, closing the tab, and even restarting the computer.

It's very simple to use:

JavaScript
// save something
localStorage.setItem("username", "Lucas");

// read it back (even after a refresh!)
const name = localStorage.getItem("username");
console.log(name); // "Lucas"

// remove one item
localStorage.removeItem("username");

// read something that was never saved
console.log(localStorage.getItem("nothingHere")); // null

There's one catch: localStorage can only store strings. If you want to save an array or an object, you have to convert it to a string first with JSON.stringify, and turn it back with JSON.parse when you load it. (That's what JSON is for! Grade 8 is paying off again.)

JavaScript
const favorites = ["burger", "pancakes", "coffee"];

// saving: object/array → string
localStorage.setItem("favorites", JSON.stringify(favorites));

// loading: string → object/array
const saved = JSON.parse(localStorage.getItem("favorites"));
console.log(saved[1]); // "pancakes"

A common pattern is to load saved data with a fallback, for the very first visit when nothing has been saved yet:

JavaScript
const saved = localStorage.getItem("favorites");
const favorites = saved ? JSON.parse(saved) : [];
Watch outlocalStorage is not a safe

Anything in localStorage can be seen (and changed) by anyone using that browser, just by opening DevTools. It's great for preferences, game progress and to-do lists. It's terrible for passwords, payment details or anything secret. Also, it only exists in that browser on that device. If the user switches to their phone, their data isn't there. (Syncing data across devices needs a server and a database, which is a College-and-beyond adventure.)

TipSee your storage

Open DevTools, go to the Application tab (in Chrome and Edge) or Storage tab (in Firefox), and look for Local Storage in the sidebar. You can see, edit and delete everything your page has saved. Very handy for debugging!

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning