Skip to article content
FrontendXLesson 24 / 30

Browser Storage

Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.

intermediate · about 35 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Choose between localStorage, sessionStorage, cookies, IndexedDB and the Cache API.
  • Store and read structured data safely with error handling.
  • Explain quota, privacy and synchronous blocking behavior.

Overview

#

Web storage

localStorage persists until cleared and is shared across tabs of the same origin. sessionStorage lasts for the tab session. Both store strings only, so objects must be serialized, and both are synchronous, which means a large read or write blocks the main thread.

snippet.js
localStorage.setItem('theme', 'dark');
console.log(localStorage.getItem('theme')); // dark

Cookies, IndexedDB and the Cache API

Cookies are small, sent with every matching request and can be marked HttpOnly and Secure, so they suit session tokens rather than bulk data. IndexedDB is asynchronous and can hold large structured data with indexes. The Cache API stores request and response pairs for offline use. Choose the smallest tool that fits the lifetime and size.

Quota, errors and privacy

Storage can throw a QuotaExceededError when full and can be unavailable in private mode or when the user blocks it. Wrap access in try and catch and provide a fallback. Never store secrets in web storage, because any script on the origin can read it. The storage event fires in other tabs, which is how cross-tab sync is built.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    What does this line print?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.javascript
    localStorage.setItem('n', 5);
    console.log(typeof localStorage.getItem('n'), localStorage.getItem('n'));
    Choose the best answer
  2. Exercise 2Explain

    Explain why localStorage is a poor fit for a large offline data set.

    starter.text
    localStorage.setItem('cache', JSON.stringify(bigArray));

    Reveal the reference answer
    reference.text
    localStorage is synchronous, so serializing and writing a large value blocks the main thread and freezes the interface. It also has a small quota of a few megabytes and stores only strings, which forces serialization overhead. IndexedDB is asynchronous, stores structured data and supports indexes, so it is the right tool for large or offline data.

    Authored expected output: the main thread blocks during the write

    The answer should name synchronous blocking, small quota and string-only storage, and point to IndexedDB as the alternative.

  3. Exercise 3Implement

    Implement `readJson(key, fallback)` so it parses a stored JSON value and returns the fallback when missing or malformed.

    starter.javascript
    function readJson(key, fallback) {
      // your code here
    }

    Reveal the reference answer
    reference.javascript
    function readJson(key, fallback) {
      try {
        const raw = localStorage.getItem(key);
        return raw === null ? fallback : JSON.parse(raw);
      } catch {
        return fallback;
      }
    }

    Authored expected output: the parsed value or the fallback

    getItem returns null for a missing key and JSON.parse throws on malformed data, so both cases are handled and the fallback keeps callers safe.

  4. Exercise 4Debug

    This save crashes when storage is full. Find and fix the bug.

    starter.javascript
    function save(key, value) {
      localStorage.setItem(key, JSON.stringify(value));
    }

    Reveal the reference answer
    reference.javascript
    function save(key, value) {
      try {
        localStorage.setItem(key, JSON.stringify(value));
        return true;
      } catch {
        return false;
      }
    }

    Authored expected output: true when saved, false when storage fails

    setItem throws a QuotaExceededError when storage is full and can throw when storage is disabled. Catching it and reporting failure lets the caller degrade gracefully instead of crashing.

  5. Exercise 5Test

    Write assertions that prove a storage wrapper round-trips an object and returns a fallback for a missing key.

    starter.javascript
    function assertEqual(actual, expected, label) {
      if (JSON.stringify(actual) !== JSON.stringify(expected)) throw new Error(label + ': unexpected value');
    }

    Reveal the reference answer
    reference.javascript
    const store = new Map();
    const readJson = (key, fallback) => {
      const raw = store.get(key);
      if (raw === undefined) return fallback;
      try { return JSON.parse(raw); } catch { return fallback; }
    };
    store.set('user', JSON.stringify({ id: 1 }));
    assertEqual(readJson('user', null), { id: 1 }, 'round-trips an object');
    assertEqual(readJson('missing', 'none'), 'none', 'returns the fallback');
    assertEqual(readJson('user', null).id, 1, 'nested value is intact');
    console.log('all assertions passed');

    Authored expected output: all assertions passed

    Serializing before storing and parsing on read restores the object. A missing key returns the fallback, and the nested value survives the round trip.

  6. Exercise 6Interview

    Where would you store an authentication token and why?

    Reveal the reference answer
    reference.text
    I prefer an HttpOnly, Secure, SameSite cookie for a session token, because JavaScript cannot read it, which removes the simplest cross-site scripting theft path. Web storage is readable by any script on the origin, so it is a weaker choice for secrets. Whichever I use, I keep lifetimes short, rotate tokens and never log them.

    The answer should compare HttpOnly cookies with web storage on script readability and should mention lifetime and rotation.

Common misconceptions

#
  • localStorage can store objects directly.
  • Cookies are a good place for large cached data.
  • Web storage is always available and never throws.

Follow-up practice

#
  • javascript-foundations-fetch-and-network
  • javascript-foundations-web-workers

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.