How Cookies, sessionStorage and localStorage works in JavaScript ?

In this article we are take care of what is cookies, sessionStorage and localStorage ? How we can perform create, read and delete operation on cookies, sessionStorage and localStorage ?

1. Cookies

Cookies is a text file stored on the local computer and it is use for tracking purpose. When client send request to server, server generate response/information client can save that response/information in cookies. It helps clients for future use. (Here client is browser.) Maximum size of cookies file is 4KB.

Create / Read / Edit / Delete cookies

We can create cookies with the document.cookie property.

document.cookie = "personName=Sagar Behare";

The cookie is deleted when browser is closed, but we can add expiry date also.

document.cookie = "personName=Sagar Behare expires=SUN, 30 Aug 2020 12:00:00 UTC";

By default, the cookie belongs to the current page but we can mention the path of the cookies.

document.cookie = "username=Sagar Behare; expires=SUN, 30 Aug 2020 12:00:00 UTC; path=/;";

We can read cookie in following ways.

var readVal = document.cookie;

We can edit or override cookies in same way that we create.

document.cookie = "username=Sagar Behare; expires=SUN, 30 Aug 2020 12:00:00 UTC; path=/;";

Deletion of cookies is very simple, just don’t mention the value.

document.cookie = "username=; expires=SUN, 30 Aug 2020 12:00:00 UTC; path=/;";

2. SessionStorage

The sessionStorage store the data only for one session. If we close the tab/browser session is closed. We can save the values in sessionStorage in terms of key-value.

Create / Read / Delete sessionStorage

Save data in sessionStorage

sessionStorage.setItem("personName", "Sagar Behare");

Read data from sessionStorage

var personName = sessionStorage.getItem("personName");

Remove data from sessionStorage

sessionStorage.removeItem("personName");

Remove all data from sessionStorage

 sessionStorage.clear();

3. LocalStorage

The localStorage store the data permanently without any expiry. We lost data only case of delete cache of browser.

Create / Read / Delete localStorage

Save data in localStorage

localStorage.setItem("personName", "Sagar Behare");

Read data from localStorage

var personName = localStorage.getItem("personName");

Remove data from localStorage

localStorage.removeItem("personName");

Remove all data from localStorage

localStorage.clear();

Leave a Reply

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