Web Storage API provides a way for browsers to store key/value pairs locally within the user's browser. It is more intuitive and secure than cookies for storing large amounts of data.
There are two main types of Web Storage:
Use localStorage when you want to save data permanently (e.g., user theme preference, saved
cart items).
// 1. Set Item
localStorage.setItem("username", "Ragini");
// 2. Get Item
const name = localStorage.getItem("username");
document.write("Stored Name:", name);
// 3. Remove Item
localStorage.removeItem("username");
// 4. Clear All
localStorage.clear();
Use sessionStorage when you want to save data temporarily for a single session (e.g., form data
while navigating between pages).
// 1. Set Item
sessionStorage.setItem("theme", "dark");
// 2. Get Item
const theme = sessionStorage.getItem("theme");
document.write("Current Theme:", theme);
/*
Note: If you close this tab and run this code again
without setting the item, it will return null.
*/
Web Storage can only store strings. To store arrays or objects, you must convert them to a string using
JSON.stringify() and parse them back using JSON.parse().
const user = { name: "Ravi", age: 25, city: "Delhi" };
// Convert object to string and store
localStorage.setItem("user", JSON.stringify(user));
// Retrieve string and convert back to object
const storedUser = JSON.parse(localStorage.getItem("user"));
document.write(storedUser.name); // "Ravi"
document.write(storedUser.city); // "Delhi"
Try saving a value, then refresh the page. Local Storage data will remain, but Session Storage data will disappear if you close the tab.
| Feature | Local Storage | Session Storage |
|---|---|---|
| Lifetime | Permanent (until manually cleared) | Temporary (until tab closed) |
| Scope | Shared across all tabs/windows | Accessible only in the current tab |
| Capacity | ~5-10 MB | ~5 MB |
Test your understanding of Web Storage.
localStorage object.username with the value "John Doe".sessionStorage object.theme.token.localStorage.let settings = { volume: 80, isMuted: false };localStorage under the key settings.getSavedSettings().settings string from localStorage.null.