Script Valley
JavaScript in the Browser: DOM, Events & APIs
Browser Storage and State ManagementLesson 5.1

localStorage vs sessionStorage: when to use each

localStorage API, sessionStorage API, setItem, getItem, removeItem, clear, storage limits, persistence rules

localStorage vs sessionStorage

Both APIs share the same interface but differ in lifetime. localStorage persists until explicitly cleared — it survives page reloads, tab closes, and browser restarts. sessionStorage is cleared when the tab is closed.

// localStorage — survives browser restart
localStorage.setItem('theme', 'dark');
console.log(localStorage.getItem('theme')); // 'dark'
localStorage.removeItem('theme');
localStorage.clear(); // removes everything

// sessionStorage — gone when tab closes
sessionStorage.setItem('draft', 'Unsaved text...');

Storage Limit

Both are limited to approximately 5 MB per origin. They are synchronous and block the main thread — avoid storing large payloads.

Storing Objects

Both APIs only store strings. Serialize objects with JSON.stringify and deserialize with JSON.parse.

const user = { id: 1, name: 'Alice' };
localStorage.setItem('user', JSON.stringify(user));

const stored = JSON.parse(localStorage.getItem('user'));
console.log(stored.name); // 'Alice'

Use localStorage for user preferences and app state that should persist. Use sessionStorage for temporary data like form drafts or wizard step state within a single session.

Up next

How to read and write browser cookies with JavaScript

Sign in to track progress