How to Store Array in localStorage in JavaScript Easily
To store an array in
localStorage, convert it to a string using JSON.stringify() before saving. To retrieve it, use JSON.parse() to convert the string back to an array.Syntax
Use localStorage.setItem(key, value) to save data and localStorage.getItem(key) to retrieve it. Since localStorage only stores strings, convert arrays to strings with JSON.stringify() before saving, and convert back with JSON.parse() when reading.
javascript
const array = ['example1', 'example2']; localStorage.setItem('myArray', JSON.stringify(array)); const retrievedArray = JSON.parse(localStorage.getItem('myArray'));
Example
This example shows how to save an array of colors to localStorage and then read it back as an array.
javascript
const colors = ['red', 'green', 'blue']; // Save array to localStorage localStorage.setItem('colors', JSON.stringify(colors)); // Retrieve array from localStorage const storedColors = JSON.parse(localStorage.getItem('colors')); console.log(storedColors);
Output
["red", "green", "blue"]
Common Pitfalls
A common mistake is trying to store the array directly without converting it to a string, which saves [object Object] or undefined. Also, forgetting to parse the string back to an array when reading causes errors or unexpected results.
javascript
/* Wrong way: */ const arr = [1, 2, 3]; localStorage.setItem('arr', arr); // Saves "1,2,3" as a string but not a JSON array const wrongArr = localStorage.getItem('arr'); console.log(typeof wrongArr); // "string" /* Right way: */ localStorage.setItem('arr', JSON.stringify(arr)); const rightArr = JSON.parse(localStorage.getItem('arr')); console.log(Array.isArray(rightArr)); // true
Output
string
true
Quick Reference
- Save array:
localStorage.setItem('key', JSON.stringify(array)) - Read array:
JSON.parse(localStorage.getItem('key')) - localStorage stores only strings.
- Always check if data exists before parsing.
Key Takeaways
Always convert arrays to strings with JSON.stringify before saving to localStorage.
Use JSON.parse to convert stored strings back to arrays when reading from localStorage.
localStorage can only store strings, so direct storage of arrays won't work as expected.
Check if the stored item exists before parsing to avoid errors.
Remember localStorage data persists until cleared, so manage storage carefully.