What is the difference between sessionStorage & localStorage

What is the difference between sessionStorage & localStorage

The sessionStorage and localStorage objects are the great objects on the client-side to store the data temporarily instead of cookies and they are two great tools for saving key-value pairs locally in the browser.

localStorage :

localStorage web objects in the browser store the information as long as the client/user does not delete them.

sessionStorage :

sessionStorage web objects in the browser store the information as long as the session goes. Usually, until the client/user closes the browser/tab.

Both objects have the same methods to perform the different operations like the below list.

  • getItem(key)
  • setItem(key, value)
  • removeItem(key)
  • clear
  • length
  • key(index)

Advantages of localStorage and sessionStorage

  • The data stored locally in the browser and can not read by any server
  • simple syntax
  • allows to store up to 10Mb data
  • Unlike cookies, web storage objects(sessionStorage & localStorage) are not sent to the server with each request.
  • Unlike cookies, the server can’t manipulate storage objects (sessionStorage & localStorage) via HTTP headers sent by the server. Everything’s done in JavaScript itself.

LocalStorage setItem example syntax :
in below syntax used local storage object and used 2 main methods. the methods are setItem and setItem. 

localStorage.setItem(key, 'testing');
undefined
localStorage.getItem(key);
"testing"


SessionStorage setItem example syntax :
in below syntax used local storage object and used 2 main methods. the methods are setItem and setItem. 

sessionStorage.setItem(key,'alltechgeeks')
undefined
sessionStorage.getItem(key)
"alltechgeeks"
Below syntax used to remove the item. we need to use a method like "removeItem" with the key.
below syntax tells to us as below steps
step 1: store a value in key
step 2: get the key-value
step 3: remove the key
step 4: check the key is available or not

sessionStorage.setItem(key,'alltechgeeks')
undefined
sessionStorage.getItem(key)
"alltechgeeks"
sessionStorage.removeItem(key)
undefined
sessionStorage.getItem(key)
null


Previous Post Next Post