How to Store Object in localStorage in JavaScript Easily
To store an object in
localStorage in JavaScript, convert it to a string using JSON.stringify() and save it with localStorage.setItem(). To retrieve it, use localStorage.getItem() and convert back to an object with JSON.parse().Syntax
Use localStorage.setItem(key, value) to save data, where key is a string identifier and value must be a string. Since objects are not strings, convert them with JSON.stringify(). To get the object back, use localStorage.getItem(key) and convert the string back to an object with JSON.parse().
javascript
localStorage.setItem('key', JSON.stringify(object)); const object = JSON.parse(localStorage.getItem('key'));
Example
This example shows how to save a user object to localStorage and then read it back as an object.
javascript
const user = { name: 'Alice', age: 30 }; // Store the object as a string localStorage.setItem('user', JSON.stringify(user)); // Retrieve the string and convert back to object const storedUser = JSON.parse(localStorage.getItem('user')); console.log(storedUser);
Output
{"name":"Alice","age":30}
Common Pitfalls
Trying to store an object directly without converting it to a string will not work because localStorage only stores strings. Also, forgetting to parse the string back to an object when retrieving will leave you with a string, not an object.
javascript
/* Wrong way: storing object directly */ const user = { name: 'Bob' }; localStorage.setItem('user', user); // stores "[object Object]" /* Right way: convert to string */ localStorage.setItem('user', JSON.stringify(user)); /* Wrong way: not parsing on retrieval */ const userString = localStorage.getItem('user'); console.log(userString.name); // undefined /* Right way: parse back to object */ const userObj = JSON.parse(userString); console.log(userObj.name); // 'Bob'
Output
undefined
Bob
Quick Reference
- Save object:
localStorage.setItem('key', JSON.stringify(obj)) - Get object:
JSON.parse(localStorage.getItem('key')) - localStorage stores only strings.
- Always stringify before saving and parse after loading.
Key Takeaways
localStorage only stores strings, so convert objects with JSON.stringify before saving.
Use JSON.parse to convert stored strings back to objects when retrieving.
Never store objects directly without stringifying, or you will get "[object Object]" stored.
Always check if the retrieved item is not null before parsing to avoid errors.
localStorage data persists even after the browser is closed, useful for saving user data.