Local Storage vs Session Storage vs Cookies in JavaScript

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

Hello everyone! In today's blog we are going to be learning about the three main ways to store data inside of a browser which are local storage, session storage and cookies. We're going to know about the differences between the three as well as how to use all three of them. So, lets get into it.


Similarities

Now, before I actually go and tell you about the actual differences, let me show you some similarities between all three. Because, at the end of the day they are all used for storing some data in a browser.

Browser Independent

All three of them are being stored on the user's actual browser that they're using, so, if they're using Google Chrome it'll be stored in their Google Chrome if they're using Firefox it'll be stored in their Firefox and so on. That means, content in cookies or local storage or session storage, that's saved on a user's browser for example Chrome will not be available on another browser on their same computer. So it's browser independent.

User Independent

Also users do not share cookies and local storage between them so if you set the local storage for a certain user, none of the other users of that site will be able to see that because it's stored on that user's computer only and nowhere else. So this is really meant for storing information related to a single user.


Differences

Now let's know about the differences between them. There's kind of two categories here. Local storage and session storage are very similar in how they interact and they're only different in a few instances, while cookies are almost completely different than the other two and are also quite a bit older than the other two.

To get started, here is the comparison chart between all three of them.

image.png

Capacity

Cookies can store only a much smaller amount of information.

The capacity here is 4 KiloBytes for most browsers. While local storage and session storage can hold 10 MegaByts and 5 MegaByts respectively. This means that cookies are going to be much smaller than local storage and session storage but that's okay for their use cases.

Browsers

Session and Local storage only supports in HTML5 supported browsers. While Cookies are supported in older browsers which support HTML4 as well. Because, they're been around for much longer. But that's not really something you have to worry about because HTML5 is in pretty much any browser being used now.

Accessibility

The data that we store Cookies and Local Storage will be available to all the tabs you open in a particular browser. For example, if you opened a website in Chrome browser, the cookies and local storage data from that website that was opened in one tab, will be accessible to all the other tabs in Chrome browser.

When it comes to Session Storage, as the name suggests, its based on the current session. That means, if you store data in session storage, the data will be accessible to only that tab but no other tabs.

Expiration

When it comes to expiration (the moment when the storage is cleared), this is where local storage and session storage really differ from each other. Session storage is for that one browsing session which is why it's called session storage and it is removed as soon as the user closes the tab where that session was set. While local storage is around forever until the user ends up deleting it or you delete it yourself inside of the code.

When it comes to cookies, you actually have to set when they expire usually. You're going to either set an infinite expiration, for example a year very very far in the future or you're going to want it to expire in a certain timeframe to see if the user has done something in that timeframe. TL;DR; you have complete control over when the cookie actually expires.

Storage Location and other

As for storage location, local storage and session storage are both on the browser like I said earlier. But cookies, while they are stored in the browser they are sent to the server every time a user requests something from the server. Whether it's an image, a HTML file or a CSS file, anything that stored as cookies get sent along with the request. Which is why they have a much smaller capacity, because all the information in the cookies gets sent to the server so if you have a lot of cookies that are really large, it'll slow down your request to the server and the requests coming back from the server. It also makes cookies really good for doing certain authentication related tasks because they actually get sent to the browser or to the server from the browser.

And these are all the major differences between each of them.


Code Examples

So now, lets look at some examples of cookies, local storage and session storage.

How to navigate to Storage Section in Chrome

We are going to use Chrome Browser for our example purposes now. In order to see where the Session, Local Storage and Cookies are saved,

Open Chrome Browser -> Open Dev Tools (f12) -> Navigate to Application Tab on top

image.png

As of now, Session Storage, Local Storage and Cookies are empty as we didn't created any.

Create, Get and Delete data in Local Storage

The data in Local Storage is in the form of key-value pairs. To deal with local storage, JavaScript provides inbuild class localStorage which contains some methods like setItem, getItem, clear, etc.

So, in order to create or technically set some data, we need to use:

localStorage.setItem('lunch', 'rice');

Here, lunch is the key and rice is its value.

image.png

And in order to Retrieve or technically get stored data, we need to use:

localStorage.getItem('lunch')

Here we need to get the value using its key.

image.png

In order to Delete or technically remove stored data, we need to use:

There are actually two ways how you can remove an item. One is using its key and another way is to remove entire thing at once.

If you want to remove a particular item using its key,

localStorage.removeItem('lunch');

image.png

If you want to remove entire local storage,

localStorage.clear()

image.png

Create, Get and Delete data in Session Storage

There is no difference between the way you handle code for loacl storage and session storage, except that the class name that contains session storage in JavaScript is sessionStorage. Even the methods that it will provide us are same.

So, I will just explain how you can create / set an item for the sake of understanding, but basically you can follow same procedure as we did for local storage.

To create or technically set some data to Session Storage, we need to use:

image.png

The examples for remaining methods like getItem, removeItem and clear are omittes as they are same as we did for local storage earlier.

Create, Get and Delete data in Cookies

Here also, we use key-value pairs to save cookies.

In order to create a cookie, we need to use:

document.cookie = "hello=true";

image.png

As you can see, there are also other parameters for a cookie like Domain, Path, Expires/Max-Age, Size, etc., which we can also pass as key value pairs while creating a cookie using document.cookie syntax.

For example,

image.png

As you can see, I have set Name and Value as doSomethingOnlyOnce=true; and also Expires as expires=Fri, 31 Dec 9999 23:59:59 GMT

In order to get or print a cookie, we need to use:

console.log(document.cookie)

When it comes to cookie, unlike session storage or local storage, we cannot get an item using its key individually. Instead all the cookies information will be stores in document.cookie in the form of a string.

image.png

In order to remove a cookie:

If we want to remove a cookie, we need to set its expiration time to past. That is, to the date that is already passed.

For example, to delete the previously created doSomethingOnlyOnce cookie, we will set its expiration to a past date;

document.cookie = "doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT";

//to remove `doSomethingOnlyOnce` cookie
document.cookie = "doSomethingOnlyOnce=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

image.png


#Conclusion

We came to the conclusion of this article. Now, you know the differences between Local Storage, Session Storage and Cookies in browsers and also how to work with them in JavaScript.

Hope you learned something new today ;)

Comments (2)

Efrén Vázquez's photo

Nice explanation, I definitely learned something new today. Thanks.

Devalla Sai Charan's photo

Glad that you learned something today🤗