What is localStorage and sessionStorage in JavaScript and How to Use it?

Nika Kharebava
3 min readApr 25, 2022

--

Do you want to show a popup to the user only one time per session? Or do you want to save some information and use it wherever you want on the website? This article is for you.

This is a feature that I have discovered not so long time ago and I think it can be really useful in some situations.

👉 What is that?

Let’s start with the general idea about both localStorage and sessionStorage. Something that they have in common is the possibility to save some kind of information and to use this information during the whole session of the user anywhere we want on the website.

What’s the difference?

Both of them are used to store data that may only be accessed by the origin that created it.

But the main difference is that when you store the data in localStorage, it doesn't expire, the data in sessionStorage is cleared at the end of the page session.

👉 Why use it?

Let’s take an example of the situation when you would like to show a popup to the user but only one time. That means that even after the page has been refreshed, the popup still won’t be shown.

Another situation could be when you need to save the information and use it throughout the whole website.

In this case, one of the best solutions would be to use localStorage or sessionStorage (depending on the situation).

Example with localStorage

As localStorage and sessionStorage have quite the same function but with different times of expiration, we will take an example of localStorage.

Let’s take a closer look at it, step by step.

1. Create a string and save some information on it.

Meaning we want to save the information about our Alert (or popup) and store the data about it (Already shown).

It can be really any names of the strings you want reflecting the current issue.

localStorage.setItem('Alert', 'Already shown');

2. Get the stored data

To be able to use the information that we have been saved, we need somehow to get it.

In this example, we have assigned it to the variable checkAlert to make its further usage easier.

const checkAlert = localStorage.getItem('Alert');

3. Use the stored data

And of course, the final step would be the practical usage of our stored data.

if(checkAlert === 'Already shown') {
console.log('Do something here')
}

4. Clear the localStorage

After using our stored data you may want to clear it all or just the one that you have used recently.

localStorage.removeItem('Alert');localStorage.clear();

And that’s it! Now you know how and when to use the localStorage and sessionStorage. 😊

Thank you for reading.

--

--

Nika Kharebava

Front-end developer specialized in Vue.Js framework. Writing about web development, side hustles, and motivation. 🌟