LocalStorage Vs SessionStorage

In this article, we will see, what are LocalStorage and SessionStorage? How we can use it? and what are the advantages and disadvantages?.

Both are an object of web storage, which allow us to save key/value pairs in the browser instead of a server. Both have some advantages and disadvantages.

What is LocalStorage?

As the name suggests, its saves/store data in client local machine in key/value pair, Its also known as DOM storage.

What is SessionStorage?

session storage saves/store data in client local machine in key/value pair for the current origin.

Both storage objects provide the same methods:

  • setItem(key, value) – which store a key/value pair.
  • getItem(key) – which gets the value by key.
  • removeItem(key) – which removes the key with its value.
  • clear() – which deletes everything from storage.
  • key(index) – which gets the key in a given position.
  • length – which returns the number of stored items.

Example

setItem(key, value)

localStorage.setItem('Name', 'Faisal');
sessionStorage.setItem('Name', 'Faisal');

getItem(key)

localStorage.getItem('Name'); 
sessionStorage.getItem('Name');

Save the object in both storage.

localStorage.setItem('Name',  JSON.stringify({name: "John"}));
sessionStorage.setItem('Name',  JSON.stringify({name: "John"}));

Get the object in both storage.

JSON.parse(localStorage.getItem('Name')); 
JSON.parse(sessionStorage.getItem('Name'));

LocalStorage Vs SessionStorage

  • Using the ratio of SessionStorage is a few frequently used then localStorage.
  • Both storage values never expired (until we cleat browser storage).
  • Both accept an only string as key and value (If you want to save an object, you need to convert in JSON serialize and then save that JSON string).
  • LocalStorage values are accessible in all tabs and windows with the same origin where sessionStorage values accessible within a browser tab.
  • LocalStorage value is accessible even after browser or machine restart where sessionStorage will be lost values.
  • Sensitive information should not be saved in both object storage, as both are stored in a client machine.

hope you guys found something useful. Please give your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article and how I could improve it.

Submit a Comment

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

Subscribe

Select Categories