1. Introduction
The Web Storage API gives JavaScript two key-value storage mechanisms built into the browser: localStorage and sessionStorage. Both let you persist data on the client without a server round trip, useful for things like theme preferences, draft form data, or caching small amounts of state.
Cricket analogy: Like a stadium offering two ways to keep a fan's seat preference without calling the box office every time — a permanent season-ticket record and a one-day match wristband, both letting a fan's choice persist locally without a server trip.
They share an identical API but differ in lifetime and scope: localStorage persists indefinitely (until explicitly cleared), while sessionStorage is cleared automatically when the browser tab is closed.
Cricket analogy: Like two identical scorebooks that work the same way but one is the permanent club archive kept forever (localStorage) while the other is a matchday chalkboard wiped clean the moment the ground closes for the day (sessionStorage).
2. Syntax
// Storing data (both accept only strings)
localStorage.setItem('theme', 'dark');
sessionStorage.setItem('draftId', '12345');
// Reading data
console.log(localStorage.getItem('theme')); // 'dark'
console.log(sessionStorage.getItem('missing')); // null if key doesn't exist
// Removing data
localStorage.removeItem('theme');
sessionStorage.clear(); // removes ALL sessionStorage keys
// Storing objects/arrays -- must serialize
const user = { id: 1, name: 'Ada' };
localStorage.setItem('user', JSON.stringify(user));
const restored = JSON.parse(localStorage.getItem('user'));
console.log(restored.name); // 'Ada'
// Listening for changes from OTHER tabs (localStorage only)
window.addEventListener('storage', (event) => {
console.log(event.key, event.oldValue, event.newValue);
});3. Explanation
localStorage data persists across browser restarts and tab closures — it remains until a script calls removeItem/clear, or the user manually clears site data; it has no expiration date by default. sessionStorage is scoped to a single tab/window session: closing that tab discards its data immediately, and each tab gets its own independent sessionStorage even for the same site (unlike localStorage, which is shared across all tabs of the same origin).
Cricket analogy: Like a club's permanent record book that survives every season until someone deliberately erases an entry (localStorage), versus each match's scoring chalkboard wiped the instant that match ends — even two simultaneous matches at the same ground keep entirely separate chalkboards (sessionStorage).
Both APIs are synchronous and store data ONLY as strings. Attempting to store a non-string value (like an object or array) silently coerces it via toString(), typically producing the useless string '[object Object]'. To store structured data, you must serialize it with JSON.stringify() before saving and parse it back with JSON.parse() after reading.
Cricket analogy: Like a scoreboard that only accepts single numeric digits typed on a keypad — jamming in a whole handwritten team roster gets silently squashed into a meaningless smudge, so you must first write the roster out as text and read it back properly.
Both storages are also limited in capacity — typically around 5-10MB per origin (varies by browser), which is much larger than cookies (~4KB) but still finite; attempting to exceed the quota throws a QuotaExceededError. Unlike cookies, data stored here is never automatically sent to the server with HTTP requests.
Cricket analogy: Like a stadium's storage room holding far more gear than a single kit bag (cookies' ~4KB) but still finite — pack past capacity and the groundskeeper turns you away (QuotaExceededError), and unlike a match report, none of that gear is automatically sent to the league office with every dispatch.
Gotcha: Both localStorage and sessionStorage only store strings. Passing an object directly to setItem() does NOT throw an error -- it silently calls toString() on it, producing the string '[object Object]', which is almost never what you want. Always JSON.stringify() before storing and JSON.parse() after retrieving structured data. Also remember: localStorage persists until explicitly cleared (survives browser restarts); sessionStorage is wiped when the tab closes.
4. Example
const settings = { theme: 'dark', fontSize: 14 };
// Common mistake: storing an object directly
localStorage.setItem('settingsRaw', settings);
console.log(localStorage.getItem('settingsRaw'));
// Correct approach: serialize first
localStorage.setItem('settings', JSON.stringify(settings));
const loaded = JSON.parse(localStorage.getItem('settings'));
console.log(loaded.theme, loaded.fontSize);
// sessionStorage for a one-time wizard step (cleared when tab closes)
sessionStorage.setItem('wizardStep', '2');
console.log(sessionStorage.getItem('wizardStep'));
// Attempting to read a never-set key
console.log(localStorage.getItem('doesNotExist'));5. Output
Console output:
[object Object] // settingsRaw stored without JSON.stringify
dark 14 // loaded.theme, loaded.fontSize after proper JSON round-trip
2 // sessionStorage.getItem('wizardStep')
null // localStorage.getItem('doesNotExist') -- key never set
Behavior notes:
- If the tab is closed and reopened (new session), sessionStorage.getItem('wizardStep')
would return null -- sessionStorage does not survive tab closure.
- If the entire browser is closed and reopened, localStorage.getItem('settings')
would still return the JSON string '{"theme":"dark","fontSize":14}' -- localStorage persists.6. Key Takeaways
- localStorage persists indefinitely across tabs and browser restarts, until explicitly cleared.
- sessionStorage is scoped to a single tab and is cleared automatically when that tab closes.
- Both store ONLY strings -- always JSON.stringify()/JSON.parse() for objects and arrays.
- Storage capacity is limited (roughly 5-10MB per origin) and throws QuotaExceededError when exceeded.
- Neither storage is automatically sent to the server (unlike cookies) and both are synchronous APIs.
- The 'storage' event on window notifies other open tabs of localStorage changes (not the tab that made the change).
Practice what you learned
1. What happens when a tab using sessionStorage is closed?
2. What data type can localStorage.setItem() actually store as values?
3. What happens if you call localStorage.setItem('key', someObject) without JSON.stringify?
4. Approximately how much storage does localStorage/sessionStorage typically provide per origin?
5. Which storage is shared across multiple tabs of the same origin at the same time?
Was this page helpful?
You May Also Like
Working with JSON in JavaScript
Learn how to convert JavaScript values to and from JSON text using JSON.stringify and JSON.parse, and understand their limitations.
DOM Manipulation in JavaScript
Learn how to select, create, modify, and remove DOM elements using JavaScript, and the key differences between the main selector APIs.
Fetch API in JavaScript
Use the Fetch API to make HTTP requests, and learn the critical gotcha that fetch does not reject on HTTP error status codes.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics