← Back to JavaScript Course | Chapter 9: Async & Web APIs | Lesson 4 of 26

JS LocalStorage and SessionStorage

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?

javascript
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()

javascript
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

javascript
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

javascript
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

javascript
localStorage.setItem("theme", "dark");   // survives closing the browser
sessionStorage.setItem("formStep", "2"); // cleared when tab closes
console.log(localStorage.getItem("theme"), sessionStorage.getItem("formStep"));

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.