30 Days Of JavaScript

Day 19: LocalStorage

Lesson 1: Saving data to LocalStorage

Change the contents of your <body> tag to:

1<div id="container">
2  <button id="add-number">Add number</button>
3  <ul id="numbers"></ul>

Then change your JavaScript to this:

1const button = document.getElementById("add-number");
2const ul = document.getElementById("numbers");
4let numbers = [];
6button.onclick = () => {
7  const number = Math.floor(Math.random() * 100);
8  numbers.push(number);
10  const li = document.createElement("li");
11  li.innerText = number;
12  ul.appendChild(li);

This is pretty familiar to you now, we just add a random number between 1 and 100 to a list. The new part to you is the line const number = Math.floor(Math.random() * 100);. Math is a class that you can call different useful functions on, let me break this down for you.

Math.random() gives us a random decimal number between 0 and 1.

We then multiply that by 100 to get a number between 0 and 100, so 0.5 becomes 50 for example. However it is likely that the number will be 0.5434 so that gives us 54.34. In this example I only want whole numbers so I round it down to the nearest whole number with Math.floor(). If you want to see what happens if we don't, then remove the Math.floor() so it's just Math.random() * 100 ... pretty gross right?

So, click the button a few times and you get a long list of numbers. Refresh the page and they go away!

Let's save the numbers to LocalStorage.

LocalStorage lets you save data as string with a key to get it back later. So in out case we will set a key called numbers with an array of numbers saved against it.

Because LocalStorage can only save strings we need to use JSON.stringify() to convert our array to a string.

Add this code to your onclick function just after the .push()

1localStorage.setItem("numbers", JSON.stringify(numbers));

Before testing it I want you to go to your developer console in Chrome, click Application across the top and then in the Storage section on the left select Local Storage and then You should see a two column table, the first column will be titled Key and the second Value. The columns should be empty.

Go ahead and click the Add Number button.

You will see a new Key appear and the value will be something like [14], click it again and you will see it is now an array with two elements.

Refresh you page.

What? Your list is empty!

That's because we need to read the data from LocalStorage and display it.


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