Learn how to use Local Storage in Javascript with an example

Published in May 2020

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 with a total price and a button that clears the cart.

This is only an example to illustrate how to use local storage. You shouldn't implement an actual checkout page with it, because 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 => {
    // item wrapper
    let item = document.createElement("DIV")
    item.innerHTML = element.name

    // item price
    let itemPrice = document.createElement("DIV")
    itemPrice.innerHTML = `$${element.price}`
    item.appendChild(itemPrice)

    // item button
    let itemButton = document.createElement("BUTTON")
    itemButton.innerHTML = "Add to cart"

    itemButton.dataset.name = element.name
    itemButton.dataset.price = element.price
    itemButton.classList.add("add-to-cart")
    item.appendChild(itemButton)

    // hr 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 item, so every time we click on an item's button, we add it to local storage (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
  // jQuery/React makes it a lot easier to do something like this
  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 have the ability to add items to a cart. Our next and final step is to create a cart page where can see the total price of our items and a button which we can clear our cart with.

<!-- 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 forEach, 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}`

  // 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 in 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 an empty basket)
  • Ability to delete an item from a cart (both only 1 occurrence of the item and all items)
  • Style the pages
  • Expand the list by adding images and descriptions to each item

Contact me on Twitter or comment on the post if you need any 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.

Thanks for reading. Happy coding! 👨‍💻👩‍💻

Level up your web development skills

Get articles, guides and interviews right in your inbox. Join a community of fellow developers.

No spam. Unsubscribe at any time.

Full Stack Heroes logo

© 2020 Full Stack Heroes