Lesson 32 of 55
HTMLWeb Storage – localStorage & sessionStorage
9 min
Course progress58%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 32 of 55
HTML9 min
Keep these ideas in mind as you work through the lesson.
Both APIs provide a simple key‑value store (strings only).
// Save a value
localStorage.setItem('theme', 'dark');
// Retrieve
const theme = localStorage.getItem('theme');
// Session‑only data
sessionStorage.setItem('temp', '123');
localStorage – Persists across sessions until cleared; shared across all tabs/windows of the same origin.sessionStorage – Clears when the tab/window closes; scoped to a single browsing context.localStorage.setItem('profile', JSON.stringify(obj));.storage event to sync changes across tabs:window.addEventListener('storage', e => {
if (e.key === 'theme') { applyTheme(e.newValue); }
});
JSON.stringify for objects)? ✅storage event used for cross‑tab sync where needed? ✅Tip: Use localStorage for UI preferences (theme, language) and sessionStorage for temporary form state that shouldn’t survive a page reload.