How to use Local Storage in Javascript + an example
Last updated on December 17, 2021
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.
1<!-- index.html -->2<div id="catalogue">3</div>
1const data = [2{3name: "Kindle",4price: 705},6{7name: "Cool Lamp",8price: 159},10{11name: "Mirror",12price: 2513}14]1516const wrapper = document.getElementById("catalogue")17data.forEach(element => {18// item wrapper19let item = document.createElement("DIV")20item.innerHTML = element.name2122// item price23let itemPrice = document.createElement("DIV")24itemPrice.innerHTML = `$${element.price}`25item.appendChild(itemPrice)2627// item button28let itemButton = document.createElement("BUTTON")29itemButton.innerHTML = "Add to cart"3031itemButton.dataset.name = element.name32itemButton.dataset.price = element.price33itemButton.classList.add("add-to-cart")34item.appendChild(itemButton)3536// hr to separate the items37item.appendChild(document.createElement("HR"))3839// insert item to the main wrapper40wrapper.appendChild(item)41return true42})
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().
1// We have to loop through all buttons and add an event listener to each individual button2// jQuery/React makes it a lot easier to do something like this3Array.from(document.getElementsByClassName("add-to-cart")).forEach(function (4element5) {6element.addEventListener("click", (e) => {7// retrieve current cart if it exists. If it doesn't create an empty cart8let cart = JSON.parse(localStorage.getItem("cart")) || [];910let newItem = {11name: e.target.dataset.name,12price: e.target.dataset.price,13};14cart.push(newItem);1516localStorage.setItem("cart", JSON.stringify(cart));17});18});19
You can go to your browser's dev tools and inspect your local storage objects.
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>
1// retrieve items from the cart2let cart = JSON.parse(localStorage.getItem("cart")) || [];3let overallPrice = 0;45if (cart.length) {6// using forEach, calculate the total price of each item within our cart array7cart.forEach((element) => {8overallPrice += parseInt(element.price, 10);9});10}11document.getElementById(12"overall-price"13).innerHTML = `Overall Price: $${overallPrice}`;1415// adds an event listener to clear our cart16document.getElementById("clear-cart").addEventListener("click", () => {17localStorage.removeItem("cart");18alert("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 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.
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.