JSON with localStorage
What is Browser Storage?
Web browsers provide built-in storage that allows a website to save data directly on a user's device — without sending it to any server. This is useful for remembering user preferences, saving a shopping cart, keeping a login state, or storing any small amount of data that should persist between page visits.
There are two types of built-in browser storage:
- localStorage — data is stored permanently until it is manually cleared. It survives browser restarts and page reloads.
- sessionStorage — data is stored only for the duration of the browser tab session. When the tab or browser is closed, the data is erased automatically.
The Problem — Storage Only Accepts Strings
Both localStorage and sessionStorage can only store text strings. They cannot directly store JavaScript objects or arrays. If an object is saved without conversion, it gets stored as the unhelpful text [object Object].
const user = { name: "Simran", age: 24 };
// WRONG — saves "[object Object]" instead of actual data
localStorage.setItem("user", user);
console.log(localStorage.getItem("user"));
// Output: [object Object] ← useless!The solution is to use JSON.stringify() before saving, and JSON.parse() after reading.
The Correct Workflow
| Step | Action | Method Used |
|---|---|---|
| Save data | Convert object to JSON string, then store | JSON.stringify() + setItem() |
| Read data | Retrieve string, then convert back to object | getItem() + JSON.parse() |
| Delete data | Remove a specific key | removeItem() |
| Clear all | Remove all stored data | clear() |
Saving an Object to localStorage
const student = {
name: "Rohit Desai",
course: "Web Development",
progress: 65
};
// Convert the object to a JSON string and save it
localStorage.setItem("studentData", JSON.stringify(student));
console.log("Data saved to localStorage.");Reading an Object from localStorage
// Retrieve the JSON string from storage
const storedData = localStorage.getItem("studentData");
// Convert the JSON string back to a JavaScript object
const student = JSON.parse(storedData);
console.log(student.name); // Output: Rohit Desai
console.log(student.progress); // Output: 65Saving and Reading an Array
Arrays work the same way — stringify before saving, parse after reading:
const wishlist = ["Laptop", "Headphones", "Keyboard"];
// Save the array
localStorage.setItem("wishlist", JSON.stringify(wishlist));
// Read the array back
const saved = JSON.parse(localStorage.getItem("wishlist"));
console.log(saved[0]); // Output: Laptop
console.log(saved.length); // Output: 3Updating Stored Data
To update stored data, read it, modify it, and save it again:
// Read existing data
const student = JSON.parse(localStorage.getItem("studentData"));
// Update the progress field
student.progress = 80;
// Save the updated object back
localStorage.setItem("studentData", JSON.stringify(student));
console.log("Progress updated to: " + student.progress); // Output: 80Adding an Item to a Stored Array
// Read existing wishlist
const wishlist = JSON.parse(localStorage.getItem("wishlist")) || [];
// Add a new item
wishlist.push("Mouse Pad");
// Save the updated array
localStorage.setItem("wishlist", JSON.stringify(wishlist));
console.log(wishlist); // Output: ["Laptop", "Headphones", "Keyboard", "Mouse Pad"]The || [] part ensures that if no wishlist is found (first time the page loads), an empty array is used instead of causing an error.
Removing Data from localStorage
// Remove a specific item
localStorage.removeItem("wishlist");
// Remove all items stored by this website
localStorage.clear();Using sessionStorage (Same Pattern)
The API for sessionStorage is identical to localStorage. The only difference is that session data is erased when the tab is closed:
// Save to sessionStorage
const cartItem = { product: "Notebook", qty: 3, price: 120 };
sessionStorage.setItem("cart", JSON.stringify(cartItem));
// Read from sessionStorage
const cart = JSON.parse(sessionStorage.getItem("cart"));
console.log(cart.product); // Output: Notebook
console.log(cart.qty); // Output: 3Handling Missing or Invalid Data Safely
Always check if the retrieved data exists before parsing it, to avoid errors when the key has not been set yet:
function getFromStorage(key) {
try {
const raw = localStorage.getItem(key);
if (raw === null) {
return null; // Key does not exist
}
return JSON.parse(raw);
} catch (e) {
console.log("Failed to read storage data: " + e);
return null;
}
}
const profile = getFromStorage("userProfile");
if (profile) {
console.log("Welcome back, " + profile.name);
} else {
console.log("No profile found.");
}localStorage vs sessionStorage — Quick Comparison
| Feature | localStorage | sessionStorage |
|---|---|---|
| Data Persistence | Permanent (until manually cleared) | Until the browser tab is closed |
| Shared Between Tabs | Yes — all tabs of the same site can access it | No — each tab has its own separate storage |
| Survives Page Reload | Yes | Yes |
| Survives Browser Restart | Yes | No |
| Typical Use | User preferences, saved settings, tokens | Temporary cart, form progress, tab-specific state |
| Storage Limit | ~5–10 MB per origin | ~5–10 MB per tab |
Key Points to Remember
- Both
localStorageandsessionStorageonly accept strings - Always use
JSON.stringify()before storing an object or array - Always use
JSON.parse()after retrieving stored data - Use
|| []or|| {}as a fallback when the item might not exist yet - Wrap storage operations in
try...catchto handle unexpected errors localStoragepersists across sessions;sessionStorageis tab-only and temporary
Summary
Browser storage combined with JSON is a practical and frequently used pattern in web development. It allows websites to remember user data locally without any server involvement. The combination of JSON.stringify() to save and JSON.parse() to retrieve makes it possible to store rich objects and arrays — not just plain text — in browser storage.
