Nishaglobal Education logo

Saving data with localStorage and JSON

Make your pages remember things after a refresh: save and load text with localStorage, store arrays and objects as JSON, handle missing or broken saved data, and know what never to store.

Lesson 12 of 1335 minQuiz: 4 questions

🎯 By the end of this lesson you will be able to:

  • Save and read strings with localStorage
  • Convert arrays and objects to and from JSON
  • Load saved data safely, with a fallback when it is missing or broken
Outline
  1. What you'll learn and why it matters
  2. localStorage basics
  3. localStorage only stores strings
  4. A safe save-and-load pattern
  5. What not to store
  6. Practice
  7. Common mistakes
  8. Recap
  9. Quiz
  10. Mark lesson complete

What you'll learn and why it matters

Refresh a page and every variable starts again from scratch. To remember a visitor's name, their dark-mode choice or their to-do list, you need to save data. Browsers give each website a small private store called localStorage. This very course saves your lesson progress there, which is why it works without an account.

localStorage basics

JavaScript
localStorage.setItem("name", "Asha");
const saved = localStorage.getItem("name");
console.log(saved);

console.log(localStorage.getItem("colour"));

localStorage.removeItem("name");
console.log(localStorage.getItem("name"));

Console (Chrome and Edge)

Asha
null
null
MethodDoes
localStorage.setItem(key, value)Saves a value under a name (the key)
localStorage.getItem(key)Reads it back, or null if nothing is saved
localStorage.removeItem(key)Deletes one saved value
localStorage.clear()Deletes everything this website saved

Saved data stays after refreshing and after closing the browser. Each website has its own storage, and it lives only in that browser on that device: a visitor using a different phone will not see it.

localStorage only stores strings

Everything is stored as text. Numbers come back as strings, and an array or object becomes useless text if you save it directly:

JavaScript
localStorage.setItem("cups", 3);
console.log(typeof localStorage.getItem("cups"));

localStorage.setItem("basket", ["chai", "samosa"]);
console.log(localStorage.getItem("basket"));

Console (Chrome and Edge)

string
chai,samosa

The fix is JSON (JavaScript Object Notation), a text format for data. JSON.stringify turns a value into JSON text, and JSON.parse turns JSON text back into a value:

JavaScript
const basket = [
  { name: "Masala chai", qty: 2 },
  { name: "Samosa", qty: 3 },
];

const text = JSON.stringify(basket);
console.log(text);
console.log(typeof text);

const back = JSON.parse(text);
console.log(back[1].name);
console.log(back.length);

Console (Chrome and Edge)

[{"name":"Masala chai","qty":2},{"name":"Samosa","qty":3}]
string
Samosa
2

A safe save-and-load pattern

Saved data might be missing (first visit), or broken (an old version of your app, or someone edited it). JSON.parse throws an error on broken text, so wrap it in try/catch and fall back to a default:

JavaScript
JSON.parse("{ broken");

The console shows this error

Uncaught SyntaxError: Expected property name or '}' in JSON at position 2 (line 1 column 3)
JavaScript
const KEY = "cafe-favourites";

function loadFavourites() {
  try {
    const text = localStorage.getItem(KEY);
    const data = text ? JSON.parse(text) : [];
    return Array.isArray(data) ? data : [];
  } catch {
    return [];
  }
}

function saveFavourites(list) {
  localStorage.setItem(KEY, JSON.stringify(list));
}

const favourites = loadFavourites();
const output = document.querySelector("#favourites");

function render() {
  output.textContent = favourites.length ? favourites.join(", ") : "No favourites yet";
}

document.querySelector("#menu").addEventListener("click", (event) => {
  const button = event.target.closest("button");
  if (!button || favourites.includes(button.textContent)) return;
  favourites.push(button.textContent);
  saveFavourites(favourites);
  render();
});

render();
Show the HTML this script works with
<div id="menu">
  <button type="button">Masala chai</button>
  <button type="button">Banana bread</button>
  <button type="button">Samosa</button>
</div>
<p>Your favourites: <span id="favourites" aria-live="polite"></span></p>

Live preview: try it

Console

Nothing logged yet.

Click some items in the preview. On your own computer, the favourites would still be there after a refresh. (In these lesson previews, saved data is kept only until you leave or press Run again, for safety.)

PieceJob
const KEY = "cafe-favourites"One name for the saved data, defined once so it is never mistyped
text ? JSON.parse(text) : []No saved data yet? Start with an empty list
Array.isArray(data)Saved data is not what we expect? Ignore it
try { … } catch { … }Broken JSON? Do not crash; use the default
Save after every changeThe saved copy always matches what is on screen

What not to store

Storage is also limited: around 5 MB per website in most browsers, which is plenty for text but not for photos or videos.

Practice

Guided exercise

Remember the visitor's name

When the form is submitted, save the name in localStorage under visitor-name and show Welcome back, NAME! in #welcome. When the page loads, show the welcome message straight away if a name is saved.

  1. Write a showWelcome(name) function that sets #welcome's text.
  2. On load, read localStorage.getItem("visitor-name") and call showWelcome if it is not null.
  3. On submit, preventDefault(), trim the name, save it, and call showWelcome.
Show the solution
Solution
const form = document.querySelector("#name-form");
const input = document.querySelector("#visitor");
const welcome = document.querySelector("#welcome");

function showWelcome(name) {
  welcome.textContent = `Welcome back, ${name}!`;
}

const savedName = localStorage.getItem("visitor-name");
if (savedName) {
  showWelcome(savedName);
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const name = input.value.trim();
  if (!name) return;
  localStorage.setItem("visitor-name", name);
  showWelcome(name);
});
Show the HTML this script works with
<form id="name-form">
  <label for="visitor">Your name</label>
  <input type="text" id="visitor">
  <button type="submit">Remember me</button>
</form>
<p id="welcome" aria-live="polite"></p>

Live preview: try it

Console

Nothing logged yet.

How to get there: A plain string needs no JSON. The load code runs once when the page opens, so a returning visitor is greeted before they type anything.

Your turn

Count the visits

Each time the page loads, add 1 to a visit counter saved in localStorage under visits, and show You have visited N times. in #visits. Remember that saved values are strings.

Show the solution
Solution
const visits = Number(localStorage.getItem("visits") ?? 0) + 1;
localStorage.setItem("visits", visits);
document.querySelector("#visits").textContent = `You have visited ${visits} times.`;
Show the HTML this script works with
<p id="visits"></p>

Live preview: try it

Console

Nothing logged yet.

How to get there: ?? (the nullish operator) uses 0 when nothing is saved yet (null). Number() converts the saved string before adding. Refresh your own page a few times to watch it grow. (Making it say *1 time* is a nice extra challenge.)

Common mistakes

Saving an array or object without JSON.stringify

You see: You get back text like [object Object] or chai,samosa

Fix: Save JSON.stringify(value) and load with JSON.parse(text).

Doing maths with a saved number

You see: "3" + 1 gives "31"

Fix: Convert with Number() after reading.

Calling JSON.parse on missing or broken data

You see: SyntaxError and a blank page

Fix: Check for null and wrap parsing in try/catch with a default.

Storing passwords or private details

You see: Anyone with access to the browser can read them

Fix: Keep localStorage for preferences, drafts and progress.

Recap

  • localStorage.setItem/getItem/removeItem save small amounts of data per website, per browser.
  • localStorage only stores strings; use JSON.stringify to save and JSON.parse to load.
  • Load safely: handle null, wrong shapes and broken JSON with a default.
  • Never store passwords or private data in localStorage.

Key terms

localStorage
A browser store where a website can keep small amounts of text that survive refreshes.
JSON
JavaScript Object Notation: a text format for data, used for saving and for web APIs.
try/catch
A way to run code that might throw an error and handle the error instead of crashing.

Check your understanding

Answer all 4 questions, then check your answers to see an explanation for each one.

  1. 1. What does `localStorage.getItem("missing")` return if nothing is saved?

  2. 2. How should you save the array `["a", "b"]` so it can be loaded back as an array?

  3. 3. Why wrap JSON.parse in try/catch when loading saved data?

  4. 4. Which is safe to keep in localStorage?

Answer all 4 questions to check.

Mark this lesson complete

Finished this lesson?

When you have worked through the examples and exercises, mark it complete to save your progress.