How do I store an array in localStorage?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Local storage provides a way to store data in key-value pairs in a user's browser, with the data persisting even after the browser window is closed. Given that localStorage only supports strings as values, storing arrays requires serialization from an array to a string format and deserialization back to an array when retrieving the data.
Storing an Array in localStorage
To store an array in localStorage, you need to serialize the array into a string. This conversion can be done using the JSON.stringify() method. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate.
Here’s a step-by-step process:
- Define the Array: Start by creating an array in JavaScript.
- Convert the Array to a String: Use
JSON.stringify()to convert the array into a JSON string. - Store the String: Use
localStorage.setItem(key, value)to store the string inlocalStorage.
Example of Storing an Array
Consider an array of items:
To store this array in localStorage:
In this code, 'fruits' is the key, and JSON.stringify(items) is the value stored in the localStorage.
Retrieving an Array from localStorage
To retrieve the stored array, you need to reverse the serialization process:
- Retrieve the String: Use
localStorage.getItem(key)to get your data back as a string. - Convert String to Array: Use
JSON.parse()on the retrieved string to convert it back into an array.
Example of Retrieving an Array
Using the previous example where we stored the array under the key 'fruits':
This snippet retrieves the string associated with the key 'fruits' from localStorage, converts it back into an array, and logs this array to the console.
Key Points Summary Table
Here's a quick summary of the key points in storing and retrieving arrays in localStorage:
| Action | Command | Description |
| Creation | const items = ['apple', 'orange']; | Defines an array. |
| Serialization | JSON.stringify(items) | Converts the array to a JSON string. |
| Store | localStorage.setItem('fruits', string) | Stores the string in localStorage. |
| Retrieve String | localStorage.getItem('fruits') | Retrieves the JSON string from localStorage. |
| Deserialization | JSON.parse(string) | Converts the JSON string back into an array. |
Additional Considerations
- Data Limits: Keep in mind that
localStoragehas a storage limit (usually about 5MB). Storing large arrays may not be ideal. - Access Across Different Tabs/WIndows: Data stored in
localStorageis not specific to a session but is specific to the browser and protocol of the website. - Security: Be careful with sensitive data, as
localStorageis accessible by any scripts running on your site and is not encrypted by default. - Browser Support: Most modern browsers support
localStoragebut always consider your audience; some older browsers may not support these features.
By following these methods and considering these points, you can effectively manage arrays in localStorage, enhancing your web application’s capabilities in terms of data storage and retrieval.
Related reading
- How do I style a <select> dropdown with only CSS?
- How do I submit disabled input in ASP.NET MVC?
- How do I test a single file using Jest?
- How do I use await inside a generator?
- How do I use AWS sdk definitions for TypeScript?
- How do I use Node.js Crypto to create a HMAC-SHA1 hash?
- How do I use $scope.$watch and $scope.$apply in AngularJS?
- How do I vertically align text in a div?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.