Back to roadmaps vanilla-js Course

Web Storage: LocalStorage & SessionStorage

Web Storage APIs allow web applications to store key-value data directly in the user's browser. It offers a larger storage capacity than cookies and doesn't affect network request payloads.

1. LocalStorage vs. SessionStorage vs. Cookies

Feature LocalStorage SessionStorage Cookies
Data Expiry Never (must be deleted via JS or cache clear) When tab/window closes Set manually
Capacity ~5MB - 10MB ~5MB ~4KB
Network Requests No No Sent to server automatically
API Easy-to-use JS methods Easy-to-use JS methods Difficult document.cookie string

2. Using LocalStorage API

LocalStorage is standard for saving long-term user preferences (like dark/light theme choices).

A. Saving and Reading Data:

  • setItem(key, value): Saves data.
  • getItem(key): Retrieves data (returns null if the key doesn't exist).
// 1. Write
localStorage.setItem('theme', 'dark');

// 2. Read
const currentTheme = localStorage.getItem('theme');
console.log(currentTheme); // "dark"

B. Deleting Data:

  • removeItem(key): Deletes a specific item.
  • clear(): Deletes ALL keys inside the site's local storage database.
localStorage.removeItem('theme');
localStorage.clear(); // Complete wipe

3. Storing Objects & Arrays (Serialization)

LocalStorage can only store strings. If you try to store an object or array directly, JavaScript converts it to "[object Object]":

const user = { name: "Alice", score: 100 };
localStorage.setItem('user', user); 
console.log(localStorage.getItem('user')); // "[object Object]" (Useless!)

To store objects or arrays, serialize them into a JSON string using JSON.stringify() before saving, and parse them back using JSON.parse() when reading:

const user = { name: "Alice", score: 100 };

// 1. Serialize and save
localStorage.setItem('user', JSON.stringify(user));

// 2. Read and deserialize
const savedUserString = localStorage.getItem('user');
const savedUser = JSON.parse(savedUserString);

console.log(savedUser.name); // "Alice"
console.log(savedUser.score); // 100 (Type is restored as Number)

4. Real-world Example: Persistent Dark Mode Toggle

const toggleBtn = document.querySelector('#theme-btn');

// 1. Check existing choice on load
const currentTheme = localStorage.getItem('theme');
if (currentTheme === 'dark') {
  document.body.classList.add('dark-mode');
}

// 2. Save preference on click
toggleBtn.addEventListener('click', () => {
  document.body.classList.toggle('dark-mode');

  if (document.body.classList.contains('dark-mode')) {
    localStorage.setItem('theme', 'dark');
  } else {
    localStorage.setItem('theme', 'light');
  }
});

In the next guide, we will cover critical performance optimization techniques including Debounce, Throttle, and memory management.

Published on Last updated: