How to use Local Storage in JavaScript

JavaScript Local Storage

Local Storage is an important part of Web Storage API and JavaScript development. It can be used to store as much data as you want. It’s blazing fast, easy to use with its key-value pairings, and it doesn’t use the server at all.

Introduction

In this post, we will cover everything you need to know about Local Storage and how to use it with JavaScript. Local Storage is one of the two storage types that you can use to store data in the browser. It’s part of the Web Storage API, which has Local storage and session storage.

What is Web Storage API?

The Web Storage API provides mechanisms by which browsers can securely store key/value pairs. It consists of two mechanisms for storing the data:

  • Session Storage – Stores data per session, meaning that it will be cleared when the browser is closed or when you wipe the session when the tab is closed.
    • Data is never transferred to the server.
    • Stores data only per session.
    • The storage limit is at most 5MB.
  • Local Storage – does the same thing but persists the data even when the browser is closed.
    • Stores data with no expiration date
    • Gets cleaned only by JavaScript or when you clear the Browser cache – Locally stored data.

How is data stored in Local Storage?

Local Storage stores the data as key-value pairs. However both key and value have to be a type of string in order to be saved to local storage. So only strings can be saved to local storage.

However that doesn’t mean that we can save other types of data, we just need to convert them to strings before saving and parse them when we pull them from the storage.

Can we access the Local Storage from the browser?

Of course, we can. To test this you can navigate to the MDN web storage app. Using the inspect element use right click and inspect element or you can use CTRL+SHIFT+I to access the developer console in the browser.

After that navigate to the Application tab, on the left side you have the sidebar you can find Local Storage there, and click on it.

Opening the developer tools to see the local storage data
Opening the developer tools to see the local storage data

In the screenshot, you can see that we have a key and value table. If you leave the dev tools open and change the values of the selects, you can see the data changing in real-time.

Showing the local storage in the web development tools
Showing the local storage in the web development tools

How to write to local storage using JavaScript?

For writing to local storage we are using the localStorage object and setItem method. The syntax is the following:

localStorage.setItem('color', 'red');

In the code above we are using the key color and the value red to write to the local storage. Now, this is the primitive type in JavaScript. If you would like to save the objects or even an array of objects to the local storage you would be using the following syntax.

const employees = [{id: 1, name: 'Djole', email: 'djordje@djolecodes.com', age: 30},{id: 2, name: 'Jane', email:'jane@test.com', age: 30}];
const stringified = JSON.stringify(employees);
localStorage.setItem('employees', stringified);

If we run this code we will have the data saved like this, even if we close the browser or refresh the page the data will still be persisted in our local storage.

Showing JavaScript object saved to local storage
Showing JavaScript object saved to local storage

This is how we see the data in the local storage after we save it.

How to get the data from local storage using JavaScript?

In order to get the data from the local storage we need to use the getItem method from the same localStorage object as we did before. As before we need to provide the key to which data we would like to get. Or we can use it as an object like you see in my console.

Using JavaScript to get the data from the local storage
Using JavaScript to get the data from the local storage

Getting data from the local storage

But as you can see for the employees we are getting our array as a string. In order to get an array as a type of data, where we can loop through that we need to parse it using JSON.parse() method.

JSON.parse(localStorage.getItem('employees'));

You can see the difference below, between parsed and not parsed data.

Showing parsed array of objects from local storage in the browser console
Showing a parsed array of objects from local storage in the browser console

How to delete the data from local storage using JavaScript?

When you wish to delete the data from the Local Storage, you need to use the following method, removeItem() and of course, provide the key of the item you want to remove from the local storage.

Using JavaScript to remove data from the local storage
Using JavaScript to remove data from the local storage

In addition to that, you need to note that you can’t remove the second employee only from the employee array that we saved to local storage just a couple of minutes before.

You will need to get the data from local storage, remove the object from the array and save it again with the same key, overriding the data we saved before.

// delete single object from array of objects in LS
const savedEmployees = JSON.parse(localStorage.getItem('employees'));
console.log('saved employees');
console.table(savedEmployees);
const updatedEmployees = savedEmployees.filter(employee => employee.id !== 2);
console.log('updated employee array');
console.table(updatedEmployees);
localStorage.setItem('employees', JSON.stringify(updatedEmployees));
console.log('get employees again')
console.table(JSON.parse(localStorage.getItem('employees')));

The code above firstly gets the employees from the local storage, secondly, it uses the filter method to remove the second object where the id is equal to two, lastly, it saves the stringified array of objects to the local storage.

We are using console.table to present the objects in a better way, if you are not using it you are missing out, check out what the console can do here.

In addition to removeItem() method, we need to mention the clear() method. Calling this method on the local storage will clear all the items from the local storage.

Conclusion

Local Storage is an extremely useful API for web developers. Especially for front-end developers, because they can use this as “storage” before they submit the data to the server. Therefore it’s useful for creating demos and prototypes.

While those are important, we can go even further and save the data like dark mode or some other user preferences to the local storage. For example, Notion is using it for that, and for saving a lot of data of your notes before storing it on the server.

What’s your Reaction?
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top