30 Days Of JavaScript

Day 19: LocalStorage

Lesson 2: Reading data from LocalStorage

In your JavaScript, replace the line let numbers = []; with this.

1const numbersString = localStorage.getItem("numbers");
2
3let numbers = JSON.parse(numbersString);
4
5numbers.forEach((number) => {
6  const li = document.createElement("li");
7  li.innerText = number;
8  ul.appendChild(li);
9});

Here we get the data from LocalStorage using the key numbers, as it's a string we need to convert it to an array using JSON.parse() and then we simply loop over each number and add it to the DOM.

Now when you refresh your page you will see the numbers on the screen.

If you click Add Number and refresh again you will see that number is saved.

But what if there is no key in LocalStorage called numbers? Let's find out.

In your developer tools console, right click on the row with the key of numbers and click Delete.

Now, refresh your page.

You will see this error message in your console:

1Uncaught TypeError: Cannot read properties of null (reading 'forEach')

Basically the line localStorage.getItem("numbers") returned null, so JSON.parse returned null and you can't call forEach on null.

Time to show you a new JavaScript thing. I could have shown you this earlier but it's easier to see it used in context.

Change this line:

1let numbers = JSON.parse(numbersString);

to

1let numbers = JSON.parse(numbersString) ?? [];

The ?? is called nullish coalescing. Which is a fancy way of saying:

If the thing on the left of the ?? is null then return what's on the right on the ??

So in our case, if JSON.parse(numbersString) is null, then set numbers to [] (an empty array)

With that in place you should find that the error goes away and you can add numbers again.

Amazing, two new concepts in one go.

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co