How to use Local Storage in Javascript with an example

Last updated on December 4, 2021

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.

<!-- index.html -->
<div id="catalogue"></div>
const data = [
  {
    name: "Kindle",
    price: 70,
  },
  {
    name: "Cool Lamp",
    price: 15,
  },
  {
    name: "Mirror",
    price: 25,
  },
];

const wrapper = document.getElementById("catalogue");
data.forEach((element) => {
  // create an item wrapper
  let item = document.createElement("div");
  item.innerHTML = element.name;

  // create item price
  let itemPrice = document.createElement("div");
  itemPrice.innerHTML = `$${element.price} USD`;
  item.appendChild(itemPrice);

  // create "Add to cart" button for each item
  let itemButton = document.createElement("button");
  itemButton.innerHTML = "Add to cart";

  // Add info to the button which we will when we want to safe it into Local Storage
  itemButton.dataset.name = element.name;
  itemButton.dataset.price = element.price;
  itemButton.classList.add("add-to-cart");
  item.appendChild(itemButton);

  // a line to separate the items
  item.appendChild(document.createElement("hr"));

  // insert item to the main wrapper
  wrapper.appendChild(item);
  return true;
});

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().

// We have to loop through all buttons and add an event listener to each individual button
Array.from(document.getElementsByClassName("add-to-cart")).forEach(function (
  element
) {
  element.addEventListener("click", (e) => {
    // retrieve current cart if it exists. If it doesn't create an empty cart
    let cart = JSON.parse(localStorage.getItem("cart")) || [];

    let newItem = {
      name: e.target.dataset.name,
      price: e.target.dataset.price,
    };
    cart.push(newItem);

    localStorage.setItem("cart", JSON.stringify(cart));
  });
});

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).

<!-- cart.html -->
<body>
  <a href="index.html">Go to catalogue page</a>
  <h1>My Cart</h1>
  <button id="clear-cart">Clear cart</button>
  <div id="overall-price">
  </div>
</body>
// retrieve items from the cart
let cart = JSON.parse(localStorage.getItem("cart")) || [];
let overallPrice = 0;

if (cart.length) {
  // using the forEach method, calculate the total price of each item within our cart array
  cart.forEach((element) => {
    overallPrice += parseInt(element.price, 10);
  });
}
document.getElementById(
  "overall-price"
).innerHTML = `Overall Price: $${overallPrice} USD`;

// adds an event listener to clear our cart
document.getElementById("clear-cart").addEventListener("click", () => {
  localStorage.removeItem("cart");
  alert("Cart is cleared!");
});

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.