JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 14: State and PersistenceLesson 68 of 150About 40 minutes

Lesson 68: Local storage and session storage

01Opening question

Refresh the page and your variables are gone. How do apps remember your theme, your draft or your cart?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

localStorage keeps strings by key. Missing keys give null and numbers come back as strings. In this sandbox storage is kept in memory for the run; in your own page it survives reloads.

localStorage.setItem("theme", "dark");
console.log(localStorage.getItem("theme"));
console.log(localStorage.getItem("missing"));
localStorage.setItem("visits", 3);
console.log(typeof localStorage.getItem("visits"));

03Objective and prerequisites

Learning objective: Save and load data with localStorage and sessionStorage, handle missing and invalid values, and know the limits of browser storage.

You need: Lesson 67: Rendering interfaces from state

Skills practised: Browser storage, localStorage and sessionStorage.

04Explanation

localStorage stores small pieces of text in the browser. Data stays after the page reloads and after the browser restarts.

setItem(key, value) saves, getItem(key) loads (or returns null if the key does not exist), removeItem(key) deletes one key and clear() deletes all.

Everything is stored as a string. A number goes in as "3" and comes back as "3"; convert it when you read it.

sessionStorage has the same methods but only lasts for one browser tab: closing the tab clears it.

05Definitions

localStorage
Browser storage for string key/value pairs that persists across reloads and restarts.
sessionStorage
Browser storage with the same API that lasts only for one tab's session.
Origin
The combination of scheme, host and port that storage and security rules are scoped to.
Quota
The maximum amount of data the browser lets a site store.
Persistence
Keeping data after the page or program that created it has stopped.

Open the full glossary

06Visual learning object

Local storage inspector. Run code that saves and loads settings, see every key and value, then simulate a page reload and watch what survives.

Loading the interactive object…

Open the full Local storage inspector page with its guided experiment.

07Examples

ex-068-01Remembering a setting Browser page (sandboxed preview)

Load with a default, save on change.

const saved = localStorage.getItem("theme") ?? "light";
let theme = saved;
document.body.dataset.theme = theme;
document.querySelector("#toggle").addEventListener("click", () => {
  theme = theme === "light" ? "dark" : "light";
  localStorage.setItem("theme", theme);
  document.body.dataset.theme = theme;
});
console.log("start:", theme);
document.querySelector("#toggle").click();
console.log("stored:", localStorage.getItem("theme"), document.body.dataset.theme);
Sample input
None
Expected output
start: light stored: dark dark
Common mistake
Reading getItem without a default and rendering null.
Try this
Clear the setting with a Reset button.
Source
examples/ex-068-01-save-theme.js

ex-068-02Everything is a string Browser page (sandboxed preview)

Numbers and booleans come back as strings; convert on read.

localStorage.setItem("visits", 1);
const visits = localStorage.getItem("visits");
console.log(visits + 1);
localStorage.setItem("visits", Number(visits) + 1);
console.log(Number(localStorage.getItem("visits")));
localStorage.setItem("muted", false);
console.log(localStorage.getItem("muted") ? "truthy" : "falsy");
Sample input
None
Expected output
11 2 truthy
Common mistake
Saving false and then testing the loaded value in an if: "false" is a non-empty, truthy string.
Try this
Store muted as "1" or "0" and read it back correctly.
Source
examples/ex-068-02-strings-only.js

ex-068-03Storage can fail Browser page (sandboxed preview)

Wrap storage in try/catch so the app still works when it is blocked or full.

function safeGet(key, fallback) {
  try {
    return localStorage.getItem(key) ?? fallback;
  } catch {
    return fallback;
  }
}
function safeSet(key, value) {
  try {
    localStorage.setItem(key, value);
    return true;
  } catch {
    return false;
  }
}
console.log(safeSet("lang", "fr"), safeGet("lang", "en"), safeGet("zone", "UTC"));
Sample input
None
Expected output
true fr UTC
Common mistake
Assuming storage is always available; some browsers block it in private windows.
Try this
Make safeSet report the error name.
Source
examples/ex-068-03-safe-access.js

ex-068-04sessionStorage versus localStorage Browser page (sandboxed preview)

Same API, different lifetime.

sessionStorage.setItem("step", "2");
localStorage.setItem("email", "kim@example.com");
console.log(sessionStorage.getItem("step"), localStorage.getItem("email"));
console.log(localStorage.length, sessionStorage.length);
localStorage.removeItem("email");
console.log(localStorage.getItem("email"));
Sample input
None
Expected output
2 kim@example.com 1 1 null
Common mistake
Using localStorage for a multi-step form's progress, so stale progress reappears next week.
Try this
List every key in localStorage with a for loop and key(i).
Source
examples/ex-068-04-session-vs-local.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

The counter shows 11

Convert stored strings.

localStorage.setItem("count", "1");
let count = localStorage.getItem("count");
count = count + 1;
localStorage.setItem("count", count);
console.log(localStorage.getItem("count"));

Save a draft

Save on input and restore on load.

localStorage.setItem("draft", "Dear team,");
const draft = document.querySelector("#draft");
// TODO 1: restore the saved draft into the textarea ("" if none)
// TODO 2: save the textarea value under "draft" on every input event
draft.value += " thanks!";
draft.dispatchEvent(new Event("input"));
console.log(localStorage.getItem("draft"));

A settings helper

Wrap storage with defaults, conversion and safety.

// Write createSettings(prefix, defaults) returning:
//   get(name)        -> stored value converted to the type of defaults[name]
//                       (number, boolean or string), or the default
//   set(name, value) -> stores String(value) under prefix + name
// Booleans are stored as "true"/"false". Wrap storage access in try/catch.

09Prediction

Commit to an answer first, then run the real code to compare.

localStorage.setItem("ok", false);
const ok = localStorage.getItem("ok");
console.log(ok, typeof ok, Boolean(ok));

What is printed?

10Debugging investigation

First-time visitors are greeted as null

Returning visitors see "Welcome back, Ada", but new visitors see "Welcome back, null".

function greet() {
  const name = localStorage.getItem("name");
  return "Welcome back, " + name;
}
document.getElementById("greeting").textContent = greet();
console.log(greet());

More cases in the Debugging Detective Laboratory

11Practical scenario

Drafts that survive a crash

Email and blog editors save your draft to local storage a moment after you stop typing. If the tab crashes or you close it by mistake, the draft is restored when you come back. Server sync happens separately, because local storage lives on only one device.

const saves = ["D", "De", "Dea", "Dear"];
console.log("writes without debounce:", saves.length);
console.log("writes with debounce:", 1);

12Knowledge check

1. What does localStorage.getItem return for a key that was never set?

  • undefined
  • null
  • ""
  • It throws

2. localStorage.setItem("n", 5); typeof localStorage.getItem("n")?

  • number
  • string
  • object
  • undefined

3. How long does sessionStorage data last?

  • Forever
  • Until the tab is closed
  • One minute
  • Until the next request

4. Why is the sound always muted after reload?

localStorage.setItem("muted", false);
if (localStorage.getItem("muted")) mute();
  • "false" is a truthy string
  • getItem is async
  • muted cannot be stored
  • setItem failed

5. Should you store an access token in localStorage?

  • Yes, it is private
  • No, any script on your pages can read it
  • Only on mobile
  • Only if it is short

6. Which is more robust?

  • Call localStorage directly everywhere
  • A small wrapper with defaults, conversion and try/catch
  • Store everything under one key with string concatenation
  • Never use storage

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • The counter shows 11: Prints 2; Stored as "2"
  • Save a draft: Prints the saved draft; Saves every edit
  • A settings helper: Prints 9 true en; Uses the prefix; false is read back as false

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-14-state-and-persistence/lesson-068-local-storage-and-session-storage/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • localStorage keeps strings across reloads; sessionStorage lasts for one tab.
  • getItem returns null for missing keys.
  • Convert values on read; booleans and numbers come back as strings.
  • Storage can fail and is readable by your scripts: handle errors and never store secrets.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation local and session storage
Context: I am learning local and session storage in JavaScript.
Task: Explain localStorage and sessionStorage, string values and defaults with small examples.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction local and session storage drill
Context: I have practised local and session storage.
Task: Give me six storage programs and ask what each prints, including booleans and numbers.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging local and session storage bug
Context: My dark mode setting turns on by itself after a reload.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation local and session storage practice
Context: I finished the local and session storage exercises.
Task: Create three exercises that save and restore settings with exact expected output.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review local and session storage review
Context: Here is my code that uses local and session storage.
Task: Review my storage code for missing defaults, string conversion bugs and secrets in storage.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.