(Storing data in the browser that persists between page reloads or sessions)
Web Storage is a browser feature that allows you to store key/value pairs in a web browser.
There are two types:
| Type | Lifespan | Scope |
|---|---|---|
localStorage | Persistent (until manually cleared) | Same-origin |
sessionStorage | Temporary (cleared on tab close) | Same-tab only |
localStorage.setItem("username", "John");const name = localStorage.getItem("username");
console.log(name); // JohnlocalStorage.removeItem("username");localStorage.clear();Works the same way as localStorage but data is lost when the browser tab is closed.
sessionStorage.setItem("sessionUser", "Alice");
const sessionUser = sessionStorage.getItem("sessionUser");
console.log(sessionUser); // AliceWeb Storage only stores strings.
To store objects/arrays, use JSON.stringify() and JSON.parse():
const user = { name: "Alex", age: 28 };
localStorage.setItem("user", JSON.stringify(user));
const userData = JSON.parse(localStorage.getItem("user"));
console.log(userData.name); // AlexlocalStorage unless manually removedlocalStorage persists data until cleared manually.sessionStorage clears when the tab is closed.setItem(), getItem(), removeItem(), and clear() methods.localStorage, and greet them on the next visit.sessionStorage and restore it if the tab refreshes.JSON.stringify() to save an object in localStorage.