LocalStorage is a simple key-value store built into every browser that lets your app remember data even after a page refresh. This lesson covers setItem() and getItem(), why everything stored must be a string (so objects need JSON.stringify/parse), the difference between localStorage and sessionStorage, and how to remove or clear stored data.
1JS LocalStorage | JavaScript Tutorial - In-Depth Guide Part 1
LocalStorage allows your app to remember things after a refresh. It's a simple key-value store that lives inside the user's browser.
// Persistent Data Storage2JS LocalStorage | JavaScript Tutorial - In-Depth Guide Part 2
To save data, use setItem(). You provide a name (key) and the data (value). Everything stored must be a String.
localStorage.setItem('theme', 'dark');
localStorage.setItem('score', '100');3JS LocalStorage | JavaScript Tutorial - In-Depth Guide Part 3
To retrieve data, use getItem(). If the key doesn exist, it returns 'null'.
const theme = localStorage.getItem('theme');
console.log(theme); // 'dark'4JS LocalStorage | JavaScript Tutorial - In-Depth Guide Part 4
To store Objects or Arrays, you must ' 'stringify' them first. Browser storage cannot read JS objects directly.
const user = { id: 1, name: 'Alex' };
localStorage.setItem('user', JSON.stringify(user));5JS LocalStorage | JavaScript Tutorial - In-Depth Guide Part 5
When reading the data back, use JSON.parse() to convert the string back into a functional JavaScript object.
const raw = localStorage.getItem('user');
const user = JSON.parse(raw);6JS LocalStorage | JavaScript Tutorial - In-Depth Guide Part 6
SessionStorage works exactly the same way, but the data is wiped as soon as the user closes the tab.
sessionStorage.setItem('temp', 'session-only');7JS LocalStorage | JavaScript Tutorial - In-Depth Guide Part 7
Maintenance: You can remove a specific item using removeItem(), or clear everything using clear().
localStorage.removeItem('theme');
localStorage.clear(); // Empty the vault8JS LocalStorage | JavaScript Tutorial - In-Depth Guide Part 8
State Persistence: Your app now has a memory. Settings, cart items, and tokens can live across sessions.
<h1>Storage: Active</h1>9JS LocalStorage | JavaScript Tutorial - In-Depth Guide Part 9
LocalStorage mastered! You
<h1>Memory: Persistent</h1>10JS LocalStorage | JavaScript Tutorial - In-Depth Guide Part 10
Next, we' Dive deep into 'JSON'βthe universal language of data exchange.
<h1>Next: JSON Deep Dive</h1>11Step-by-Step Breakdown
LocalStorage allows your app to remember things after a refresh. It's a simple key-value store that lives inside the user's browser.
To save data, use setItem(). You provide a name (key) and the data (value). Everything stored must be a String.
To retrieve data, use getItem(). If the key doesn exist, it returns 'null'.
Checkpoint: If you store a Number in localStorage, what type will it be when you retrieve it?
- βNumber
- βString
To store Objects or Arrays, you must ' 'stringify' them first. Browser storage cannot read JS objects directly.
When reading the data back, use JSON.parse() to convert the string back into a functional JavaScript object.
SessionStorage works exactly the same way, but the data is wiped as soon as the user closes the tab.
Checkpoint: Which storage survives even after the computer is restarted?
- βLocalStorage
- βSessionStorage
Maintenance: You can remove a specific item using removeItem(), or clear everything using clear().
State Persistence: Your app now has a memory. Settings, cart items, and tokens can live across sessions.
LocalStorage mastered! You
Next, we' Dive deep into 'JSON'βthe universal language of data exchange.
Level Up π
Advanced cheat sheets, SEO tricks, and interview prep for this topic.
Browser Support
Fully supported.
Fully supported.
Fully supported.
Fully supported.
Accessibility (A11y)
1Restoring a Saved Preference Must Also Restore Its Visual and ARIA State Together
If a user's saved 'high contrast' or 'reduced motion' preference is read from localStorage but the corresponding class and ARIA attributes aren't applied until after the page has already rendered, users relying on that setting see (or hear) a flash of the wrong state before it corrects itself.
SEO Implications
- 1
LocalStorage Is Invisible to Search Engine Crawlers and Should Never Hold Indexable Content
Data in localStorage exists only in a specific user's browser and is never sent to or seen by a server or crawler. Any content that needs to be indexed by search engines must be rendered into the actual HTML response, not stored or generated exclusively through client-side localStorage logic.
Best Practices
Always Wrap JSON.parse() of Stored Data in try/catch
Data in localStorage can be edited or corrupted by browser extensions, manual devtools tampering, or an older version of your app's schema. Parsing it without error handling risks crashing the app on a single bad value β wrap it in try/catch and fall back to a sensible default.
Never Store Sensitive Data Like Passwords or Full Auth Secrets in localStorage
Anything in localStorage is readable by any JavaScript running on that page, including from a successful XSS attack. Prefer httpOnly cookies for sensitive session tokens, and only keep non-sensitive UI state (like theme or draft form data) in localStorage.
Frequent Bugs
Retrieving a stored object logs '[object Object]' instead of the actual data.
localStorage can only store strings β passing a raw object directly to setItem() implicitly calls .toString() on it, producing the generic '[object Object]' text. Convert it with JSON.stringify() before saving, and JSON.parse() it back after retrieving.
Real-World Examples
Persisting a Shopping Cart Across Page Reloads
An e-commerce site needed the shopping cart to survive a page refresh without requiring a login, so cart contents were saved to localStorage on every change and restored on page load, with a fallback for first-time visitors.
function saveCart(cartItems) {
localStorage.setItem('cart', JSON.stringify(cartItems));
}
function loadCart() {
try {
const raw = localStorage.getItem('cart');
return raw ? JSON.parse(raw) : [];
} catch (e) {
console.error('Cart data corrupted, resetting.', e);
return [];
}
}