Question

How to Store Arrays in localStorage with JavaScript

htmljavascriptarrayslocal-storage

Question

How can I store a JavaScript array in localStorage and retrieve it later?

Without localStorage, this code works:

const names = [];
names[0] = prompt("New member name?");

However, I want the names array to persist in localStorage. Why do attempts such as the following not work, and what is the correct approach?

const localStorage[names] = [];
localStorage.names[0] = prompt("New member name?");

Short Answer

By the end of this page, you will understand why localStorage cannot store arrays directly, how to convert an array to JSON before saving it, and how to safely convert it back into an array when reading it.

Concept

localStorage is a browser feature for saving small pieces of data that should remain available after a page reload or browser restart. It stores data as string key-value pairs only.

A JavaScript array is not a string. Therefore, this will not preserve an array's structure:

localStorage.setItem("names", ["Ada", "Lin"]);

JavaScript converts the array to the string "Ada,Lin". This loses important information. For example, an array containing commas or nested values cannot reliably be reconstructed from that string.

Use JSON instead:

  • JSON.stringify(value) converts an array or plain object into a JSON string.
  • JSON.parse(text) converts a valid JSON string back into an array or object.
const names = ["Ada", "Lin"];
localStorage.setItem("names", JSON.stringify(names));

const savedNames = JSON.parse(localStorage.getItem("names"));

This matters because real applications often need to persist user preferences, draft form data, shopping-cart items, completed tasks, and other structured data between visits.

Mental Model

Think of localStorage as a filing cabinet that accepts only sheets of paper containing text.

An array is like a tray holding several labelled items. You cannot put the tray directly into the filing cabinet. JSON.stringify is the process of writing an accurate description of the tray and its contents onto a sheet of paper. JSON.parse reads that description later and rebuilds the tray.

  • Array: ['Ada', 'Lin']
  • Stored text: '["Ada","Lin"]'
  • Rebuilt array: ['Ada', 'Lin']
Take Quiz

Syntax and Examples

Save an array with localStorage.setItem() and JSON.stringify():

const names = [];
const newName = prompt("New member name?");

names.push(newName);
localStorage.setItem("names", JSON.stringify(names));

Read it later with localStorage.getItem() and JSON.parse():

const storedNames = localStorage.getItem("names");
const names = storedNames ? JSON.parse(storedNames) : [];

console.log(names);

The conditional expression is important:

storedNames ? JSON.parse(storedNames) : []

When the key does not exist, getItem() returns null. Parsing null is not appropriate when your code expects an array, so use an empty array as the first-run default.

A complete add-and-save example:

const names = JSON.parse(localStorage.getItem("names") || "[]");
const newName = prompt("New member name?");

if (newName !== null && newName.trim() !== "") {
  names.push(newName.trim());
  localStorage.setItem("names", JSON.stringify(names));
}

The || "[]" fallback provides valid JSON representing an empty array when no saved value exists.

Step by Step Execution

Consider this code:

const names = JSON.parse(localStorage.getItem("names") || "[]");
names.push("Mina");
localStorage.setItem("names", JSON.stringify(names));

Suppose there is no names value in storage yet.

  1. localStorage.getItem("names") returns null because the key is absent.
  2. null || "[]" evaluates to "[]".
  3. JSON.parse("[]") creates a new empty array: [].
  4. names.push("Mina") changes the array to ["Mina"].
  5. JSON.stringify(names) converts it into the string '["Mina"]'.
  6. localStorage.setItem("names", ...) saves that string under the key names.

On a later page load:

  1. getItem("names") returns '["Mina"]'.
  2. JSON.parse(...) reconstructs the JavaScript array ["Mina"].
  3. You can call array methods such as push, map, and filter on it.

Real World Use Cases

Common uses for arrays in localStorage include:

  • To-do lists: Save an array of tasks so they remain after a refresh.
  • Shopping carts: Keep product IDs and quantities for a visitor who has not checked out.
  • Recently viewed items: Store a limited list of page or product IDs.
  • User interface preferences: Save selected columns, dismissed announcements, or favorite categories.
  • Draft content: Temporarily save text-editor or form drafts in the browser.

For example, a recently viewed product list can be stored as an array of IDs:

const recentProductIds = [14, 28, 91];
localStorage.setItem("recentProductIds", JSON.stringify(recentProductIds));
Take Quiz

Real Codebase Usage

In real projects, code usually reads storage through a small helper function rather than repeating JSON.parse everywhere.

function loadArray(key) {
  const rawValue = localStorage.getItem(key);

  if (rawValue === null) {
    return [];
  }

  try {
    const value = JSON.parse(rawValue);
    return Array.isArray(value) ? value : [];
  } catch {
    return [];
  }
}

function saveArray(key, value) {
  localStorage.setItem(key, JSON.stringify(value));
}

Usage:

const names = loadArray("names");
names.push("Mina");
saveArray("names", names);

This pattern provides:

  • A default value when nothing has been saved yet.
  • Validation with Array.isArray() in case the key contains a different JSON value.
  • Error handling if stored JSON is malformed.
  • A single location to update storage-related behavior.

Applications also commonly use a guard clause before saving user input:

if (!newName || newName.trim() === "") {
  return;
}

Do not treat localStorage as a secure database. Any script running on the same site can generally read it, so never store passwords, access tokens that require strong protection, or other sensitive information there.

Common Mistakes

Trying to declare a variable with localStorage[...]

This is invalid JavaScript:

const localStorage[names] = [];

A variable name cannot contain square brackets. Use localStorage.setItem(key, value) to save a value.

Treating a stored value as an array

This does not work as intended:

localStorage.names[0] = "Ada";

localStorage.names is a stored string, not a live JavaScript array. Read it, parse it, update the array, then save it again.

const names = JSON.parse(localStorage.getItem("names") || "[]");
names[0] = "Ada";
localStorage.setItem("names", JSON.stringify(names));

Forgetting JSON.stringify() when saving

localStorage.setItem("names", ["Ada", "Lin"]);

This stores "Ada,Lin", not JSON. Always stringify structured data.

localStorage.setItem("names", JSON.stringify(["Ada", "Lin"]));

Forgetting JSON.parse() when reading

const names = localStorage.getItem("names");
names.push("Mina"); // Error: names is a string

Parse the stored text first.

Parsing a missing value without a fallback

const names = JSON.parse(localStorage.getItem("names"));

If the key is missing, use a fallback such as "[]" or explicitly check for null first.

Assuming localStorage is private or unlimited

Storage capacity varies by browser, and users can clear it. It is also accessible to JavaScript on the same origin. Store only small, non-sensitive data and make your application handle missing data.

Comparisons

FeaturelocalStoragesessionStorageJavaScript variable
Value typeStrings onlyStrings onlyAny JavaScript value
Persists after refreshYesYesNo
Persists after browser/tab closesUsually yesNo, usually cleared when the tab session endsNo
Shared across tabs on the same originYesNo, separated per tabNo
Structured data supportUse JSON.stringify / JSON.parseUse JSON.stringify / JSON.parseNative arrays and objects
OperationPurpose
localStorage.setItem("key", value)Save a string value
localStorage.getItem("key")Read a value or get null if missing
localStorage.removeItem("key")Remove one saved value
localStorage.clear()Remove all values for the current origin
JSON.stringify(array)Convert an array to storable text
JSON.parse(text)Convert JSON text back to an array
Take Quiz

Cheat Sheet

// Save an array
localStorage.setItem("names", JSON.stringify(names));

// Load an array, defaulting to [] when absent
const names = JSON.parse(localStorage.getItem("names") || "[]");

// Add an item and save the changed array
names.push("Ada");
localStorage.setItem("names", JSON.stringify(names));

// Remove the saved array
localStorage.removeItem("names");

Rules:

  • localStorage stores strings, not arrays or objects.
  • Use a stable string key such as "names".
  • Parse data after reading it.
  • Stringify data before writing it.
  • Provide a fallback for a missing key.
  • Wrap parsing in try...catch when storage may contain invalid or old data.
  • Do not store secrets or sensitive personal data in localStorage.

FAQ

Can localStorage store an array directly?

No. It stores strings. Convert the array to a JSON string with JSON.stringify() first.

Why does localStorage.getItem() return null?

It returns null when no value has been saved under that key. Use a fallback such as localStorage.getItem("names") || "[]".

Do I need to save the array after every change?

Yes. Updating an in-memory array with push, pop, or assignment does not automatically update localStorage.

Can localStorage store arrays of objects?

Yes, provided the objects contain JSON-compatible values.

const tasks = [{ id: 1, title: "Read", done: false }];
localStorage.setItem("tasks", JSON.stringify(tasks));

Why should I not use localStorage.names?

Property-style access can work in some cases, but getItem and setItem are clearer and avoid conflicts with built-in properties or unusual key names.

Does localStorage expire automatically?

No standard expiration time is applied. Data remains until your code removes it, the user clears browser data, or browser storage is cleared.

Can JSON.stringify save functions, dates, or undefined values exactly?

No. JSON supports basic data such as strings, numbers, booleans, null, arrays, and plain objects. Functions and undefined are not preserved, and dates become strings.

Take Quiz

Mini Project

Description

Build a small member-name saver. It loads previously saved names from localStorage, lets the user add a name through a prompt, and saves the updated list for the next page load. This demonstrates the complete read, update, and write cycle used by browser-based lists.

Goal

Create a script that persists a list of member names in localStorage.

Requirements

Load the existing names array from localStorage when the script starts. Use an empty array when no saved names exist. Ask the user for one new member name. Do not save blank names or a cancelled prompt. Add a valid name to the array and save the updated array. Display the current list in the console.

Take Quiz

Keep learning

Related questions

View more