Saving Arrays and Objects

localStorage keeps only text. When you give setItem() something else, it turns it into text by itself, and not always in a way you can use:

localStorage.setItem("books", ["Momo", "Matilda"]);
console.log(localStorage.getItem("books"));

localStorage.setItem("book", { title: "Momo" });
console.log(localStorage.getItem("book"));
Momo,Matilda
[object Object]

The array has become the text Momo,Matilda, which isn't an array any more, and the object is lost completely. You already know the way around it: JSON. When you save a value, turn it into JSON text with JSON.stringify(), and when you read it, turn it back into an array or object with JSON.parse():

localStorage.setItem("books", JSON.stringify(books));

const saved = localStorage.getItem("books");
if (saved !== null) {
    books = JSON.parse(saved);
}

When the page opens, it starts with an empty array (let books = [];) and replaces it with the saved one if there is one. The check for null matters here: JSON.parse(null) returns null, and the first books.push() would end with TypeError: Cannot read properties of null (reading 'push').

And when should the page save? Every time the array changes: after adding, removing or changing an item. It's easiest to write a function saveBooks() and call it right after each change, next to the call that shows the list again.

Typical mistakes:

  • Saving without JSON.stringify(). It seems to work, but when the page opens again, JSON.parse("Momo,Matilda") ends with a SyntaxError.
  • Saving at the start of the script, before the saved data is read. That overwrites what was saved with an empty array.

Instructions

Every time a book is added, save the array books in localStorage under the key books, as JSON text.

When the page opens, load the saved books, if there are any, so that the list shows them. Add a few books and click Run: the list stays.

When clearButton is clicked, empty the array books, delete the saved books with removeItem() and show the empty list.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

8/9

Next