Imagine you want to remember a user's preferences — like their chosen theme or language — without asking them every time they visit. HTML5 gives you two mechanisms for this: localStorage and sessionStorage. Both let you store key-value pairs right in the browser, no server needed.
localStorage: Data That Persists
localStorage stores data with no expiration — it stays there until you explicitly remove it. This is perfect for user preferences, saved settings, or any data you want to survive browser restarts and page reloads.
<script>
// Save data
localStorage.setItem('theme', 'dark');
localStorage.setItem('username', 'Alice');
// Read data back
const theme = localStorage.getItem('theme');
console.log(theme); // "dark"
// Remove a specific item
localStorage.removeItem('username');
// Clear everything
localStorage.clear();
</script>
sessionStorage: Data That Dies with the Tab
sessionStorage works the same way, but the data only lives for the duration of the browser tab. Close the tab, and it is gone. This is useful for temporary state like form data that should reset when the user leaves the page.
<script>
sessionStorage.setItem('cartCount', '3');
const count = sessionStorage.getItem('cartCount');
console.log(count); // "3"
// This data disappears when the tab closes
</script>
Storing Objects and Arrays
Both storage APIs only store strings. If you want to save an object or array, you need to convert it to a JSON string with JSON.stringify() and parse it back with JSON.parse() when you read it.
<script>
const user = { name: 'Alice', age: 25, city: 'Lagos' };
localStorage.setItem('user', JSON.stringify(user));
const saved = JSON.parse(localStorage.getItem('user'));
console.log(saved.name); // "Alice"
</script>
Storage Limits and Events
Browsers typically allow 5-10 MB of storage per origin. You can listen for storage events to react when data changes in another tab or window. This is great for keeping multiple tabs in sync.
<script>
window.addEventListener('storage', (e) => {
console.log(`Key: ${e.key}, Old: ${e.oldValue}, New: ${e.newValue}`);
});
// When another tab does localStorage.setItem('theme', 'light'),
// this event fires in the current tab.
</script>