Web Storage allows websites to store data directly in the user’s browser in the form of key–value pairs. It is more secure and provides more space than cookies, and it is not sent to the server on every request.
Both are part of the Web Storage API and are available through the window object in modern browsers.
localStorage.setItem(key, value) – store a value.localStorage.getItem(key) – read a value.localStorage.removeItem(key) – remove a single key.localStorage.clear() – clear everything for that origin.Data survives page reloads and browser restarts until the user clears it (or your script does).
localStorage, but data exists only for the current tab.Great for data that should not leak between tabs, such as temporary tokens or form steps.
Basic operations with localStorage to store and retrieve a username.
// Set item
localStorage.setItem('username', 'Ashish');
// Get item
let user = localStorage.getItem('username');
console.log(user); // "Ashish"
// Remove item
localStorage.removeItem('username');
// Clear all items
localStorage.clear();
Same API, but values exist only for the life of the browser tab/session.
// Set item
sessionStorage.setItem('token', '12345');
// Get item
let token = sessionStorage.getItem('token');
console.log(token); // "12345"
// Remove item
sessionStorage.removeItem('token');
// Clear all items
sessionStorage.clear();
Because storage only handles strings, objects must be converted using JSON.
const preferences = {
theme: 'dark',
fontSize: 16
};
// Store object as JSON string
localStorage.setItem('prefs', JSON.stringify(preferences));
// Read string and convert back to object
const stored = localStorage.getItem('prefs');
const parsedPrefs = JSON.parse(stored);
console.log(parsedPrefs.theme); // "dark"
console.log(parsedPrefs.fontSize); // 16
"username" is saved and can be read on any page from the same origin, even after reloading or reopening the browser."token" exists only in the currently open tab. Closing that tab clears the value automatically.JSON.stringify(), stored, and then converted back with JSON.parse().localStorage.clear() or sessionStorage.clear() is called, all keys for that storage type are removed for that origin.JSON.stringify() for complex data (arrays/objects) and JSON.parse() when reading them back.try...catch; trying to store too much can throw a QuotaExceededError.localStorage, and greets the user automatically on the next visit.sessionStorage to store a temporary token or a step number in a multi-step form, and observe how it resets when the tab is closed.JSON.stringify(), then read and apply those preferences with JSON.parse() on page load.