How to use Local Storage in Javascript with an example

Last updated on June 22, 2022

Already know the basics of Local Storage and instead you'd like how to use it in React? You can check out this tutorial instead.

Local Storage is a useful way of storing data within your browser. The data is stored across browser sessions - which means that you can refresh the page and go to different pages without losing the information which is stored inside Local Storage.

If you are building a simple app or you want to store non-sensitive information within your website, local storage is a great addition to your skillset.

It is supported by most major browsers. To demonstrate how you can save and read information, we are going to build a simple e-commerce website with a cart page. I will build it in plain HTML and Javascript, but you are welcome to do this example in a framework of your choice.

Local Storage and its methods

Local storage is similar to Session storage except that Local Storage is not cleared whenever the page is closed. This means that you can close the browser, but the data stored in Local Storage will still be there.

setItem()

localStorage.setItem(keyName, keyValue) method writes a key/value pair to localStorage. The keyName and keyValue should be strings, so if you want to save an array or object to keyValue, you will need to convert them into strings using Array.prototype.toString() or JSON.stringify(object).

getItem()

localStorage.getItem(keyName) retrieves an item from the localStorage by keyName. Note that it will return null if the key does not exist.

The return value is the keyValue associated with the keyName. The return value will be a string, so if you have saved an array or object (like described above) you will need to convert them to the relevant data type in order to use them.

removeItem()

localStorage.removeItem(keyName) will remove the provided key from localStorage.

clear()

localStorage.clear() clears all keys from local storage. It basically resets localStorage.

key()

localStorage.key(index) returns the keyName at the given index within localStorage.

Building a simple e-commerce website with a checkout page

Now let's put our newly acquired knowledge into practice. We will have two pages, one with a list of products with a name, price, and "Add to cart" button and a cart page where we can showcase the total price and a button that would clear the data from our Local Storage.

This is only an example used to illustrate how to use local storage. You shouldn't implement an actual checkout page with it, due to security reasons. For example, the user can easily change the price number within the Dev Tools.

The setup

Let's begin by building a simple page with one div where we can insert our catalogue into using Javascript.

Within our Javascript code, we create a simple list of products which we then loop through and insert our objects with the buttons onto the DOM inside the "catalogue" div.

html
1
<!-- index.html -->
2
<div id="catalogue">
3
</div>
javascript
1
const data = [
2
{
3
name: "Kindle",
4
price: 70
5
},
6
{
7
name: "Cool Lamp",
8
price: 15
9
},
10
{
11
name: "Mirror",
12
price: 25
13
}
14
]
15
16
const wrapper = document.getElementById("catalogue")
17
data.forEach(element => {
18
// create an item wrapper
19
let item = document.createElement("div")
20
item.innerHTML = element.name
21
22
// create item price
23
let itemPrice = document.createElement("div")
24
itemPrice.innerHTML = `$${element.price} USD`
25
item.appendChild(itemPrice)
26
27
// create "Add to cart" button for each item
28
let itemButton = document.createElement("button")
29
itemButton.innerHTML = "Add to cart"
30
31
// Add info to the button which we will when we want to safe it into Local Storage
32
itemButton.dataset.name = element.name
33
itemButton.dataset.price = element.price
34
itemButton.classList.add("add-to-cart")
35
item.appendChild(itemButton)
36
37
// a line to separate the items
38
item.appendChild(document.createElement("hr"))
39
40
// insert item to the main wrapper
41
wrapper.appendChild(item)
42
return true
43
})

Add an event listener

Our next task is to add a click event listener to the product's button, so every time we click on it, we can add its info to Local Storage (ie our cart).

As mentioned above, when you retrieve an object from Local Storage, it will be in a string format. You need to convert it back into an object using JSON.parse().

You also need to convert the object into a string before you save it into Local Storage. You can do it using JSON.stringify().

javascript
1
// We have to loop through all buttons and add an event listener to each individual button
2
Array.from(document.getElementsByClassName("add-to-cart")).forEach(function (
3
element
4
) {
5
element.addEventListener("click", (e) => {
6
// retrieve current cart if it exists. If it doesn't create an empty cart
7
let cart = JSON.parse(localStorage.getItem("cart")) || [];
8
9
let newItem = {
10
name: e.target.dataset.name,
11
price: e.target.dataset.price,
12
};
13
cart.push(newItem);
14
15
localStorage.setItem("cart", JSON.stringify(cart));
16
});
17
});

You can go to your browser's dev tools and inspect your Local Storage objects.

Creating the cart page

We now can add items to a cart. Our next and final step is to create a cart page where we can see the total price of our items and a button so we can reset the cart (ie delete our data in Local Storage altogether).

html
1
<!-- cart.html -->
2
<body>
3
<a href="index.html">Go to catalogue page</a>
4
<h1>My Cart</h1>
5
<button id="clear-cart">Clear cart</button>
6
<div id="overall-price">
7
</div>
8
</body>
javascript
1
// retrieve items from the cart
2
let cart = JSON.parse(localStorage.getItem("cart")) || [];
3
let overallPrice = 0;
4
5
if (cart.length) {
6
// using the forEach method, calculate the total price of each item within our cart array
7
cart.forEach((element) => {
8
overallPrice += parseInt(element.price, 10);
9
});
10
}
11
document.getElementById(
12
"overall-price"
13
).innerHTML = `Overall Price: $${overallPrice} USD`;
14
15
// adds an event listener to clear our cart
16
document.getElementById("clear-cart").addEventListener("click", () => {
17
localStorage.removeItem("cart");
18
alert("Cart is cleared!");
19
});

You did it! If you want to make this a more complete example and gain a deeper understanding of Local Storage, here are some extra tasks you can do:

  • Ability to see how many times we have selected a certain item on the cart page
  • When you clear your entire basket, that should be reflected on the page (currently you need to refresh to page to see the empty basket)
  • Ability to delete an item from a cart (both only 1 occurrence of the item and all items)
  • Expand the list by adding images and descriptions to each item an

Contact me on Twitter or comment below if you need any extra help.

Limitations of Local Storage

It might be convenient to use Local Storage, but you should be aware when you shouldn't use it. In general, do not use localStorage to store sensitive information such as user or purchase data as it can be accessed and modified by anybody.

It also has a 10MB limit in Google Chrome, but browsers like Opera might increase the storage place if needed. In general, 10MB should be enough for whatever you are doing, as this amount of space can store millions of string characters.

Invite us to your inbox.

Articles, guides and interviews about web development and career progression.

Max 1-2x times per month.