Local Storage and Session Storage
You'll learn how to store simple key-value data in the browser that persists across page refreshes or only for the current session.
What Are They?
The browser provides two storage mechanisms for saving string data directly in the user's browser:
localStorage keeps data indefinitely — it survives page refreshes, browser restarts, and even computer reboots. The data only disappears if the user manually clears it or your code deletes it.
sessionStorage keeps data only for the current tab's session — it vanishes when the user closes that specific tab or window.
Think of localStorage like saving a note on your fridge that stays there until you remove it, while sessionStorage is like a sticky note that falls off when you close the door.
Basic Usage
Both have identical APIs:
// Storing data (values must be strings)
localStorage.setItem('username', 'Alice');
sessionStorage.setItem('tempToken', 'xyz123');
// Retrieving data
const name = localStorage.getItem('username'); // "Alice"
const token = sessionStorage.getItem('tempToken'); // "xyz123"
// Removing data
localStorage.removeItem('username');
// Clearing all data
localStorage.clear();
Important Limitations
Both storage types only accept strings. For objects or arrays, you'll need to convert them first using JSON.stringify() when storing and JSON.parse() when retrieving.
Data is scoped to the origin (protocol + domain + port), so different websites can't access each other's storage.
Key Takeaway: Use localStorage for data that should persist between visits (like user preferences) and sessionStorage for temporary data tied to a single browsing session (like form drafts or temporary filters).