Introduction

Today, we are going to discuss the role of local storage and session storage in modern web development. it plays a crucial role in managing and storing the data temporarily on the browser.

Now, we will discuss their similarities and differences in detail. One thing that surprises you is that the data survives on a page refresh( for session storage ) and even on a browser restart ( for local storage).

Session Storage

The object stores data only for a session, if you close the browser the data will be lost. It persists data only till the end of the session.

Local storage

The object stores data that persists even when the user closes the browser tab or even when you close the browser. The object stores data without any expiration date. It only gets cleared.

Before using web storage, check browser support for localStorage and sessionStorage.

if (typeof(Storage) !== "undefined") {
  //  localStorage/sessionStorage Supports.
} else {
  // Sorry! No localStorage/sessionStorage support..
}

Six (6) built-in methods and properties

setItem()

This method is used to store values in the local storage/session storage, it takes two arguments first key name and the second value. If the key exists, the value will be updated.

localStorage.setItem("name","abhishek");
localStorage.setItem("age","19");
const info ={
Name:'Abhishek Chadha',
Grade:'A'
};
localStorage.setItem("personelinfo",JSON.stringify(info));

setItem()

sessionStorage.setItem("name","abhishek");
sessionStorage.setItem("age","19")
const info ={
Name:'Abhishek Chadha',
Grade:'A'
};
sessionStorage.setItem("personelinfo",JSON.stringify(info));

setItem()

getItem()

This method is used to access or retrieve the data from the session storage/local storage. A key is used as a parameter.

getItem()

getItem()

removeItem()

This method is used to delete an item from session storage/local storage.

removeItem()

key()

This method retrieves a value from a specific location. The index can be passed as a parameter.

key()

length()

This method is used to get the no of key-value pairs in session storage/local storage.

length()

clear()

The clear method will remove all items from local storage/session storage.

clear()

Conclusion