Question
How to Store JavaScript Objects in localStorage and sessionStorage
Question
I want to store a JavaScript object in HTML5 localStorage, but the object seems to be converted into a string.
I can store and retrieve primitive JavaScript values and arrays, but plain objects do not seem to behave the way I expected. Should storing objects work directly?
Here is the code:
var testObject = { one: 1, two: 2, three: 3 };
console.log('typeof testObject: ' + typeof testObject);
console.log('testObject properties:');
for (var prop in testObject) {
console.log(' ' + prop + ': ' + testObject[prop]);
}
// Put the object into storage
localStorage.setItem('testObject', testObject);
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('typeof retrievedObject: ' + typeof retrievedObject);
console.log('Value of retrievedObject: ' + retrievedObject);
The console output is:
typeof testObject: object
testObject properties:
one: 1
two: 2
three: 3
typeof retrievedObject: string
Value of retrievedObject: [object Object]
It looks like setItem() converts the value to a string before storing it.
I see the same behavior in Safari, Chrome, and Firefox, so I assume this is my misunderstanding of Web Storage rather than a browser bug.
Why does this happen, and what is the easiest way to store and retrieve objects correctly using localStorage or sessionStorage?
Short Answer
By the end of this page, you will understand that localStorage and sessionStorage store strings only, not JavaScript objects directly. You will learn how to save objects with JSON.stringify(), restore them with JSON.parse(), avoid common mistakes, and use this pattern safely in real projects.
Concept
localStorage and sessionStorage are part of the Web Storage API. They provide simple key-value storage in the browser.
The important rule is:
- Keys are strings
- Values are strings
That means if you pass an object to setItem(), JavaScript converts it to a string first. A plain object becomes:
"[object Object]"
That string is not a real object anymore. It is just text, so when you read it back with getItem(), you get a string.
To store an object properly, you need to:
- Convert the object into a JSON string with
JSON.stringify() - Save that string in storage
- Convert it back into an object with
JSON.parse()when reading it
Example:
const user = { name: 'Ava', age: 28 };
localStorage.setItem('user', JSON.stringify(user));
const storedUser = .(.());
.(storedUser.);
Mental Model
Think of localStorage like a notebook that only accepts text.
- If you hand it a number, it writes the number as text
- If you hand it a boolean, it writes
"true"or"false" - If you hand it an object, it cannot keep the object structure by itself, so it writes the object's default text form:
"[object Object]"
JSON.stringify() is like translating your object into a text format that preserves its structure.
JSON.parse() is like reading that text and rebuilding the original object.
So the flow is:
- Object in memory ->
JSON.stringify()-> JSON text in storage - JSON text from storage ->
JSON.parse()-> Object in memory
Syntax and Examples
The basic pattern is:
localStorage.setItem('key', JSON.stringify(value));
const value = JSON.parse(localStorage.getItem('key'));
Store and retrieve an object
const testObject = { one: 1, two: 2, three: 3 };
localStorage.setItem('testObject', JSON.stringify(testObject));
const retrievedObject = JSON.parse(localStorage.getItem('testObject'));
console.log(typeof retrievedObject); // object
console.log(retrievedObject.one); // 1
console.(retrievedObject.);
.(retrievedObject.);
Step by Step Execution
Consider this example:
const cart = { items: 3, total: 49.99 };
localStorage.setItem('cart', JSON.stringify(cart));
const raw = localStorage.getItem('cart');
const parsed = JSON.parse(raw);
console.log(raw);
console.log(parsed.total);
Step by step:
cartis created as a normal JavaScript object:
{ items: 3, total: 49.99 }
JSON.stringify(cart)converts it to a string:
'{"items":3,"total":49.99}'
Real World Use Cases
Here are common situations where developers store objects in browser storage:
User preferences
const preferences = {
language: 'en',
darkMode: true,
sidebarOpen: false
};
Store these so the app remembers settings after refresh.
Shopping cart data
const cart = {
items: [
{ id: 101, quantity: 2 },
{ id: 205, quantity: 1 }
],
coupon: 'SAVE10'
};
Useful for preserving cart contents between page reloads.
Form drafts
const draft = {
title: 'My article',
body: 'Draft content here...'
};
Helpful in note-taking apps, CMS editors, or long forms.
Cached API responses
cachedUser = {
: ,
: ,
:
};
Real Codebase Usage
In real projects, developers usually do more than just call JSON.stringify() and JSON.parse() directly.
Common wrapper functions
A common pattern is to centralize storage logic:
function saveToStorage(key, value) {
localStorage.setItem(key, JSON.stringify(value));
}
function loadFromStorage(key) {
const value = localStorage.getItem(key);
return value ? JSON.parse(value) : null;
}
This avoids repeating the same code everywhere.
Guard clauses for missing data
function loadCart() {
const saved = localStorage.getItem('cart');
if (!saved) return { items: [] };
return .(saved);
}
Common Mistakes
1. Storing objects without JSON.stringify()
Broken:
const user = { name: 'Sam' };
localStorage.setItem('user', user);
Result:
"[object Object]"
Fix:
localStorage.setItem('user', JSON.stringify(user));
2. Forgetting to JSON.parse() after reading
Broken:
localStorage.setItem('user', JSON.stringify({ name: 'Sam' }));
const user = localStorage.getItem('user');
console.(user.);
Comparisons
| Concept | What it stores | Persists after browser restart? | Best for |
|---|---|---|---|
localStorage | Strings | Yes | Preferences, carts, cached small data |
sessionStorage | Strings | No | Tab-specific temporary state |
| JavaScript variable | Any JS value | No | In-memory runtime data |
| Cookie | Strings | Usually yes, if configured | Small server-related data |
localStorage vs sessionStorage
localStorage.(, );
.(, );
Cheat Sheet
// Store an object
localStorage.setItem('key', JSON.stringify(obj));
// Read an object
const raw = localStorage.getItem('key');
const obj = raw ? JSON.parse(raw) : null;
// Remove an item
localStorage.removeItem('key');
// Clear all storage
localStorage.clear();
Rules
localStoragestores strings only- Objects must be converted with
JSON.stringify() - Read them back with
JSON.parse() - The same pattern applies to
sessionStorage
Common results
localStorage.setItem('x', { a: });
.();
FAQ
Can localStorage store JavaScript objects directly?
No. It stores strings only. Use JSON.stringify() before saving and JSON.parse() after reading.
Why do I get "[object Object]" in localStorage?
Because the object was converted using normal string conversion instead of JSON serialization.
Does this also apply to sessionStorage?
Yes. sessionStorage also stores string values only.
Can I store arrays in localStorage?
Yes, but you should still use JSON. Arrays are commonly stored with JSON.stringify() and restored with JSON.parse().
What happens if the key does not exist?
getItem() returns null. You should check for that before parsing.
Can I store functions, dates, or class instances?
Not reliably in their original form. JSON works best with plain data objects, arrays, strings, numbers, booleans, and null.
Is localStorage a good place for sensitive data?
Usually no. Sensitive data in browser storage can be exposed if your site has security issues such as XSS.
Mini Project
Description
Build a small browser-based preferences saver. The app stores a user's display settings in localStorage and restores them when the page loads. This demonstrates the full cycle of converting an object to JSON, saving it, reading it back, and updating the UI from stored data.
Goal
Create a page that saves and restores a user preferences object using localStorage and JSON methods.
Requirements
- Create a preferences object with at least
username,theme, andnotificationsproperties. - Save the preferences object to
localStoragewhen the user clicks a button. - Load the saved preferences from
localStoragewhen the page starts. - Display the loaded values on the page.
- Handle the case where no saved preferences exist yet.
Keep learning
Related questions
Can You Style Half a Character in CSS? Text Effects with CSS and JavaScript
Learn how to style half of a character using CSS and JavaScript, including overlay techniques for dynamic text effects.
Get Screen, Page, and Browser Window Size in JavaScript
Learn how to get screen size, viewport size, page size, and scroll position in JavaScript across major browsers.
Get the Selected Radio Button Value with jQuery
Learn how to find which radio button is selected in jQuery and get its value with simple examples and common mistakes.