LocalStorage in JavaScript

LocalStorage in JavaScript

In this article, we will take a look at the localStorage API in Javascript which is used to store and access the data inside the browser.

You might want to store some data in the browser to provide the user with a smooth experience or you don't want to make request to the backend everytime whenever the user reloads the page and that's where the localStorage API comes in handy to store the data inside the browser. The data stored using the localStorage has no expiry date until the user has cleared the browser cache. Now, we will take a look at how to store, access and remove data in localStorage API.

To store data we use localStorage.setItem("key", "value")

const myName = "Aadhi";

localStorage.setItem("name", myName);

To read the data we use localStorage.getItem("key")

localStorage.getItem("name");

To remove a single item we use localStorage.removeItem("key")

localStorage.removeItem("name");

To clear everything inside localStorage

localStorage.clear();

Note: localStorage API can only store data in the form of strings.

To store arrays or objects we first need to change it to strings. We can do that by using JSON.stringify()

const arr = ["Aadhi", 1999]

localStorage.setItem("myInfo", JSON.stringify(arr))

To access the stringified object or array we use JSON.parse()

JSON.parse(localStorage.getItem("myInfo"))

As localStorage is a synchronous operation storing huge amount of data will lead to performance issues.

Note: Please, don't store any sensitive information inside localStorage. Always store sensitive information on the backend.

That's it. Hope, everyone enjoys the article.

Thanks for reading.