LocalStorage
Web Development
JavaScript
Data Storage
Programming Tips

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.

Browse interview questions

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:

  1. Define the Array: Start by creating an array in JavaScript.
  2. Convert the Array to a String: Use JSON.stringify() to convert the array into a JSON string.
  3. Store the String: Use localStorage.setItem(key, value) to store the string in localStorage.

Example of Storing an Array

Consider an array of items:

javascript
const items = ['apple', 'orange', 'banana'];

To store this array in localStorage:

javascript
localStorage.setItem('fruits', JSON.stringify(items));

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:

  1. Retrieve the String: Use localStorage.getItem(key) to get your data back as a string.
  2. 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':

javascript
const storedItems = JSON.parse(localStorage.getItem('fruits'));
console.log(storedItems); // Outputs: ["apple", "orange", "banana"]

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:

ActionCommandDescription
Creationconst items = ['apple', 'orange'];Defines an array.
SerializationJSON.stringify(items)Converts the array to a JSON string.
StorelocalStorage.setItem('fruits', string)Stores the string in localStorage.
Retrieve StringlocalStorage.getItem('fruits')Retrieves the JSON string from localStorage.
DeserializationJSON.parse(string)Converts the JSON string back into an array.

Additional Considerations

  • Data Limits: Keep in mind that localStorage has a storage limit (usually about 5MB). Storing large arrays may not be ideal.
  • Access Across Different Tabs/WIndows: Data stored in localStorage is not specific to a session but is specific to the browser and protocol of the website.
  • Security: Be careful with sensitive data, as localStorage is accessible by any scripts running on your site and is not encrypted by default.
  • Browser Support: Most modern browsers support localStorage but 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
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Browse interview questions

All Rights Reserved.