JS LocalStorage and SessionStorage
In this page:
What Is Storage?
Web storage lets a browser save small amounts of string data. Unlike cookies, storage data isn't automatically sent with every HTTP request, which makes it better suited for larger amounts of client-side-only data.
Example: What Is Storage?
localStorage.setItem("visits", "1");
console.log(localStorage.getItem("visits")); // not sent with every HTTP request, unlike cookies
setItem() and getItem()
Use setItem() to save a value and getItem() to read it. Both methods only work with strings — trying to store a number or object directly will store its coerced string form, which is rarely what you want.
Example: setItem() and getItem()
localStorage.setItem("age", 30); // stored as string "30"
console.log(typeof localStorage.getItem("age"));
Objects and JSON
Storage values are strings, so use JSON.stringify() and JSON.parse() for objects. Storing an object means calling JSON.stringify() before setItem() and JSON.parse() after getItem(), since storage can't hold structured data directly.
Example: Objects and JSON
const user = { name: "Sam", age: 30 };
localStorage.setItem("user", JSON.stringify(user));
const loaded = JSON.parse(localStorage.getItem("user"));
console.log(loaded.name);
Remove and Clear
removeItem() deletes one key. clear() removes all keys from a storage area. Because clear() wipes every key for that origin, prefer removeItem() with a specific key when you only need to delete one piece of stored data.
Example: Remove and Clear
localStorage.setItem("a", "1");
localStorage.setItem("b", "2");
localStorage.removeItem("a");
console.log(localStorage.getItem("a")); // null
localStorage.clear();
console.log(localStorage.getItem("b")); // null
Local vs Session
localStorage normally remains after the browser is closed. sessionStorage is tied to the tab session. Choose localStorage for data that should survive across visits (like a saved theme preference) and sessionStorage for data that should reset when the tab closes.
Example: Local vs Session
localStorage.setItem("theme", "dark"); // survives closing the browser
sessionStorage.setItem("formStep", "2"); // cleared when tab closes
console.log(localStorage.getItem("theme"), sessionStorage.getItem("formStep"));
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS JSON
- JS Regular Expressions
- JS Fetch API
- JS LocalStorage and SessionStorage
- JS Cookies
- JS setTimeout and setInterval
- JS Event Loop
- JS Web Workers
- JS Service Workers
- JS AJAX
- JS AJAX Intro
- JS AJAX XMLHttp
- JS AJAX Request
- JS AJAX Response
- JS AJAX XML
- JS AJAX PHP
- JS AJAX Database
- JS JSONP
- JS RegExp Flags
- JS RegExp Classes
- JS RegExp Metachars
- JS RegExp Assertions
- JS RegExp Groups
- JS RegExp Quantifiers
- JS JSON HTML
- JS JSON vs XML