LocalStorage

A web storage API that allows JavaScript to store key-value pairs in the browser with no expiration time, persisting even after the browser is closed.

Overview

LocalStorage provides a simple way to store data in the browser that persists across browser sessions. Unlike cookies, the data is never sent to the server and has a much larger storage limit (usually 5-10MB). It's perfect for storing user preferences, cached data, or application state.

Example

javascript
// Store data
localStorage.setItem('username', 'Alice');
localStorage.setItem('theme', 'dark');

// Store objects (must stringify)
const user = { name: 'Alice', age: 30 };
localStorage.setItem('user', JSON.stringify(user));

// Retrieve data
const username = localStorage.getItem('username');
console.log(username); // 'Alice'

// Retrieve and parse object
const storedUser = JSON.parse(localStorage.getItem('user'));
console.log(storedUser.name); // 'Alice'

// Remove item
localStorage.removeItem('username');

// Clear all
localStorage.clear();

// Check if key exists
if (localStorage.getItem('theme')) {
  // Theme is set
}

// Get number of items
console.log(localStorage.length);

Key Points

  • Stores data with no expiration
  • 5-10MB storage limit per domain
  • Synchronous API (blocking)
  • Stores strings only (use JSON.stringify/parse for objects)
  • Accessible only from same origin

Learn More