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.
Learning objective: Save and load data with localStorage and sessionStorage, handle missing and invalid values, and know the limits of browser storage.
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.
Storage is per origin (scheme, host and port). Other sites cannot read it, but any script on your own pages can, so never store secrets or tokens there.
Quotas are small (about 5 MB per origin) and writes can throw a QuotaExceededError; private browsing may also block storage. Wrap reads and writes in try/catch and keep the app working without it.
Storage calls are synchronous and block the page. Save small things only, and debounce frequent writes such as drafts.
Version your keys (app:v2:settings) so a new release can ignore or migrate data saved by an old one. The storage event tells other tabs of the same site that a value changed.
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.
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());
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?
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
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.
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 explanationlocal 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 predictionlocal 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.
Debugginglocal 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 generationlocal 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 reviewlocal 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.