Local Storage & Session Storage
Modern websites often remember user preferences — like login state, theme choice, or recently viewed items.
JavaScript provides Web Storage to store small pieces of data directly in the browser.
What Is Web Storage?
Web Storage allows you to store key–value pairs inside the user's browser.
This data stays available even after page refreshes, depending on the storage type used.
Types of Web Storage
- Local Storage – persists until manually cleared
- Session Storage – exists only for the session
Local Storage
Local Storage stores data permanently in the browser (unless cleared by the user or code).
localStorage.setItem("theme", "dark");
This value remains even after closing and reopening the browser.
Reading from Local Storage
let theme = localStorage.getItem("theme");
console.log(theme);
If the key does not exist, the result is null.
Removing Data from Local Storage
localStorage.removeItem("theme");
This deletes only the specified key.
Session Storage
Session Storage works the same way as Local Storage, but the data is cleared when the browser tab is closed.
sessionStorage.setItem("user", "Sreekanth");
This is useful for temporary data.
Local vs Session Storage
- Local Storage persists across sessions
- Session Storage resets when the tab closes
- Both store data as strings
Real-World Example
Saving a user's theme preference:
let theme = "dark";
localStorage.setItem("theme", theme);
When the user returns, the site remembers their choice.
Common Beginner Mistakes
- Trying to store complex objects directly
- Forgetting that values are stored as strings
- Using storage for sensitive data
Never store passwords or confidential data in Web Storage.
Thumb Rules
- Use Local Storage for persistent preferences
- Use Session Storage for temporary data
- Always validate stored values
- Keep storage usage minimal
What Comes Next?
Now that you can store data in the browser, the next step is understanding the browser environment itself.
In the next lesson, we will learn about the BOM.