Careeroza
Web Storage
localStorage and sessionStorage
Both store strings by key in the browser. localStorage survives restarts; sessionStorage lasts until the tab closes. Store objects as JSON.
localStorage.setItem("theme", "dark");
localStorage.getItem("theme"); // "dark"
localStorage.removeItem("theme");
const cart = [{ id: 1, qty: 2 }];
localStorage.setItem("cart", JSON.stringify(cart));
const saved = JSON.parse(localStorage.getItem("cart") ?? "[]");Example: Remember a Preference
Example
Run it in the code runner and reload: your choice is remembered (storage may be blocked in the lesson preview).
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<label><input type="checkbox" id="dark"> Dark mode</label>
<script>
const box = document.getElementById("dark");
const apply = () => (document.body.style.background = box.checked ? "#1d2a35" : "white",
document.body.style.color = box.checked ? "white" : "black");
try {
box.checked = localStorage.getItem("dark") === "1";
box.addEventListener("change", () => { localStorage.setItem("dark", box.checked ? "1" : "0"); apply(); });
} catch (e) {
box.addEventListener("change", apply);
}
apply();
</script>
</body>
</html>Result
Note: Never store passwords or access tokens in web storage: any script on the page can read it.