Local Storage and JSON

Course 2 · Ch 7
Local Storage and JSON: Persisting Data Between Page Loads
Everything in memory disappears on refresh — localStorage is the simplest way to make data survive

Every variable in every chapter so far has vanished the instant the page reloads. localStorage is a browser-provided key/value store that survives refreshes, browser restarts, even the computer rebooting — and combined with JSON.stringify/JSON.parse (the same JSON mechanics behind Fundamentals Chapter 10's fetch), it can store more than just plain text.

Storing and Reading a String

localStorage.setItem("username", "Philip"); const name = localStorage.getItem("username"); console.log(name); // "Philip" — still there even after a page refresh

setItem(key, value) saves a value under a string key; getItem(key) reads it back. Reload the page and run getItem("username") again — the value is still there, unlike every variable from earlier chapters, which would be reset to nothing on reload.

localStorage only stores strings
localStorage.setItem("age", 35) silently converts 35 to the string "35" — reading it back with getItem gives a string, not a number. Trying to store an object directly (setItem("user", { name: "Philip" })) doesn't work either: it gets converted to the unhelpful string "[object Object]", losing all the actual data.

JSON.stringify — Turning Data Into a Storable String

const user = { name: "Philip", age: 35, isStudent: true }; const jsonString = JSON.stringify(user); console.log(jsonString); // '{"name":"Philip","age":35,"isStudent":true}' localStorage.setItem("user", jsonString);

JSON.stringify converts an object or array into a JSON-formatted string — text that fully represents the original data's structure and values, safe to store as a single localStorage string. This is the same conversion that happens automatically inside a fetch request body when sending JSON data to a server.

JSON.parse — Turning It Back Into Real Data

const jsonString = localStorage.getItem("user"); const user = JSON.parse(jsonString); console.log(user.name); // "Philip" — a real object again, with real dot-notation access console.log(typeof user.age); // "number" — NOT a string, unlike storing a number directly

JSON.parse does the reverse: a JSON string back into a real, usable JavaScript object — with correct types preserved (age comes back as an actual number, not the string "35"). This stringify/parse pair is exactly how Fundamentals Chapter 10's response.json() works internally.

The Complete Save/Load Pattern

function saveSettings(settings) { localStorage.setItem("settings", JSON.stringify(settings)); } function loadSettings() { const stored = localStorage.getItem("settings"); return stored ? JSON.parse(stored) : null; // null if nothing was ever saved } saveSettings({ theme: "dark", fontSize: 16 }); const settings = loadSettings(); console.log(settings.theme); // "dark"

localStorage.getItem returns null if the key was never set — checking for that with stored ? ... : null (Fundamentals Chapter 3's ternary) avoids calling JSON.parse(null), which would throw rather than returning something sensible.

Removing and Clearing Storage

localStorage.removeItem("username"); // removes just one key localStorage.clear(); // removes EVERYTHING this site has stored

removeItem deletes a single key, the direct equivalent of delete obj.key from Fundamentals Chapter 7; clear() wipes every key the current site has stored in localStorage entirely.

localStorage vs sessionStorage
localStorage persists indefinitely, across browser restarts, until explicitly cleared. sessionStorage shares the exact same API (setItem/getItem/removeItem/clear) but is wiped automatically when the browser tab closes — useful for data that should only last for the current visit.
ToolPurpose
localStorage.setItem(key, value)Save a string value, persisting across reloads
localStorage.getItem(key)Read a stored value; returns null if never set
JSON.stringify(value)Convert an object/array into a storable JSON string
JSON.parse(jsonString)Convert a JSON string back into a real object/array
localStorage.removeItem(key) / .clear()Delete one key / delete everything

Coding Challenges

Challenge 1

Save the string "dark" under the key "theme" using localStorage.setItem. Read it back with getItem and log it. Then use removeItem to delete it, and log getItem("theme") again to confirm it now returns null.

📄 View solution
Challenge 2

Create an object task = { title: "Buy milk", done: false }. Save it to localStorage under "task1" using JSON.stringify. Read it back, parse it with JSON.parse, and log task.title and typeof task.done to confirm the boolean type survived the round trip.

📄 View solution
Challenge 3

Write functions saveTodos(todos) and loadTodos() using the save/load pattern from this chapter, where todos is an array of strings. saveTodos should stringify and store the array; loadTodos should return the parsed array, or an empty array [] (not null) if nothing has been saved yet. Save 3 todos, then load and log them.

📄 View solution

Chapter 7 Quick Reference

  • localStorage.setItem(key, value) — saves a STRING, persisting across reloads/restarts
  • localStorage.getItem(key) — reads it back; returns null if the key was never set
  • JSON.stringify(value) — converts an object/array into a JSON string for storage
  • JSON.parse(jsonString) — converts a JSON string back into a real object/array, types intact
  • localStorage.removeItem(key) — deletes one key; clear() — deletes everything for this site
  • sessionStorage — same API, but wiped when the browser tab closes
  • Always guard JSON.parse against a null/missing value before calling it
  • This completes JavaScript Intermediate. Advanced begins with modules — import/export and bundlers conceptually.