Useful Cheatsheetsusefulcheatsheets.com
JavaScript Storage
Chapter 09 · Page 73
Beginner

JavaScript Storage

Use localStorage and sessionStorage to persist data in the browser across sessions and refreshes.

TL;DR

  1. 01Use localStorage to save data that persists across browser sessions.
  2. 02Use sessionStorage for temporary data cleared when the tab closes.
  3. 03Store only strings by converting objects to JSON first.

Tips

  1. 01Use localStorage for user preferences and sessionStorage for temporary state, then sync between tabs using storage events.
  2. 02Wrap JSON.parse() calls in a try/catch block because corrupted or manually edited storage data throws exceptions.

Warnings

  1. 01Avoid storing sensitive data like passwords or tokens in localStorage because it is vulnerable to cross-site scripting attacks.
  2. 02Saving an object directly without JSON.stringify() stores the useless string [object Object] instead of your data.
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Storage
Chapter 09 · Page 74
Beginner

JavaScript Storage

(continued)

localStorage Basics

  • localStorage

    A browser storage object that persists key-value data indefinitely with no expiration date.

    localStorage.setItem("username", "Alice");
    const name = localStorage.getItem("username");
  • removeItem()

    Deletes a specific key-value pair from storage by providing the key name.

    localStorage.removeItem("username");
  • clear()

    Wipes all stored key-value data for the current domain origin at once.

    localStorage.clear();
  • in operator

    Checks if a specific storage key exists in the storage object dictionary.

    if ("username" in localStorage) {
      console.log("Key exists!");
    }
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Storage
Chapter 09 · Page 75
Beginner

JavaScript Storage

(continued)

sessionStorage

  • sessionStorage

    A storage object that maintains key-value data for the duration of the page session.

    sessionStorage.setItem("tabId", "12345");
    const id = sessionStorage.getItem("tabId");
  • Tab isolation

    Maintains separate storage instances for each open browser tab, even on the same origin.

    // A new window starts a fresh storage instance
  • Identical API

    Shares the same storage interface, methods, and behaviors as localStorage.

    sessionStorage.setItem("key", "val");
    sessionStorage.removeItem("key");
    sessionStorage.clear();
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Storage
Chapter 09 · Page 76
Beginner

JavaScript Storage

(continued)

Storing Objects

  • JSON.stringify()

    Serializes objects or arrays into strings before saving them to browser storage.

    const user = { name: "Alice", age: 30 };
    localStorage.setItem("user", JSON.stringify(user));
  • JSON.parse()

    Deserializes stored JSON strings back into usable JavaScript objects or arrays.

    const raw = localStorage.getItem("user");
    const user = JSON.parse(raw);
    console.log(user.name); // "Alice"
  • Error handling

    Wraps JSON parsing in try-catch blocks to prevent crashes on invalid data formats.

    try {
      const user = JSON.parse(localStorage.getItem("user"));
    } catch (e) {
      console.error("Invalid JSON stored");
    }
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Storage
Chapter 09 · Page 77
Beginner

JavaScript Storage

(continued)

Storage Events

  • storage event

    Listens for storage changes on the window object across different origin tabs.

    window.addEventListener("storage", e => {
      console.log(`${e.key} changed to ${e.newValue}`);
    });
  • Cross-tab sync

    Notifies other open tabs on the same origin immediately when storage updates.

    // Tab A writes to storage
    localStorage.setItem("theme", "dark");
    
    // Tab B receives storage event automatically
  • StorageEvent object

    Exposes modified keys, new values, old values, and the target storage area.

    window.addEventListener("storage", e => {
      if (e.key === "theme") {
        applyTheme(e.newValue);
      }
    });
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Storage
Chapter 09 · Page 78
Beginner

JavaScript Storage

(continued)

Best Practices

  • QuotaExceededError

    Catches browser storage limit exceptions to avoid crashing applications when disk space runs out.

    try {
      localStorage.setItem("key", largeData);
    } catch (e) {
      if (e.name === "QuotaExceededError") {
        console.warn("Storage limit exceeded!");
      }
    }
  • Namespacing

    Prefixes storage keys to prevent overlap conflicts with other third-party scripts.

    localStorage.setItem("myApp_theme", "dark");
    localStorage.setItem("myApp_lang", "en");
  • Security warnings

    Avoids storing sensitive authentication tokens, passwords, or personal data in plaintext storage.

    // Avoid storing JWTs in localStorage
    // Secure: use HTTP-only, secure cookies instead
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Storage
Chapter 09 · Page 79
Beginner

JavaScript Storage

(FAQ)

FAQ

The localStorage object persists data indefinitely across browser sessions and tabs. In contrast, sessionStorage is cleared automatically when the tab or window closes. Use localStorage for user preferences and sessionStorage for temporary form state.

Convert the object to a string using JSON.stringify() before saving it with localStorage.setItem(). Read it back by parsing the string with JSON.parse(). Skipping this serialization step mistakenly stores the string [object Object].

Listen for the storage event on the window object. This event fires in all other tabs when localStorage is updated. It provides the modified key, oldValue, and newValue to sync your frontend.

The localStorage.setItem() method throws a QuotaExceededError when storage limit is reached. This limit is typically five megabytes. Always wrap write operations in try/catch blocks to handle storage failures gracefully.

Call localStorage.removeItem('key') to delete a specific item. Alternatively, use localStorage.clear() to wipe all stored key-value pairs for the origin. Use clear() with caution as it clears data from all scripts.

Useful Cheatsheetsusefulcheatsheets.com
JavaScript Storage
Chapter 09 · Page 80
Beginner

JavaScript Storage

(In Practice)
In Practice

Managing User Preference Storage

Saves and loads user interface preferences using JSON serialization while handling storage quotas and parsing errors.

  1. 01Create a preferences object containing the user's selected theme and font size.
  2. 02Serialize the preferences object to a JSON string and store it safely in localStorage.
  3. 03Catch any storage quota errors that might arise if the browser storage is full.
  4. 04Retrieve and parse the stored JSON string back into a JavaScript object when the page loads.
  5. 05Fallback to default values if preferences are missing or the string contains invalid data.
function savePreferences(theme, fontSize) { 
  const prefs = { theme, fontSize };
  try {
    const serialized = JSON.stringify(prefs);
    localStorage.setItem("user_prefs", serialized);
  } catch (e) {
    console.error("Save failed", e);
  }
}

function loadPreferences() {
  const raw = localStorage.getItem("user_prefs");
  if (!raw) return { theme: "light", fontSize: 14 };
  try {
    return JSON.parse(raw);
  } catch (e) {
    return { theme: "light", fontSize: 14 };
  }
}
Takeaway

Always serialize objects before storing them and use try-catch to safeguard against corrupted data or full storage.