We build your ideas. Contact us for Mobile/Web App Development. Write us @ contact@milanjeet.com

localStorage and sessionStorage in JavaScript

Localstorage and Sessionstorage

JavaScript is very powerful and popular client side scripting language as it provides so many features to smoothly and reliably play with the data, do desired operations and achieve the results. Now a days, a JavaScript developers are surrounded with JavaScript frameworks like jQuery, React, Angular, Vue and many more. Web storage i.e. localStorage and sessionStorage in Javascript play a vital role. Many developers and the learner who are learning javascript are still confused in difference between localStorage and sessionStroage. In the blog, we are going to finally learn the difference.

The Web Storage API provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using cookies.

There mechanism are available via the global Window object window.localStorage and window.sessionStorage.

localStorage

localStorage is a space which is available through out the execution with no expiration date and gets cleared only through JavaScript or clearing the browser cache or Localstorage data.

Data stored in localStorage is available even after the browser is closed, even after system turns off and on or restart.

The storage size is depends on the browser but it has the maximum storage limit among sessionStoage and cookie. 10 MB is the localStorage size in Google Chrome browser.

Example:

localStorage.setItem('my_localstoage_variable', 'Local Storage Value');

setItem & getItem

setItem is used to set the value in local/sessionStorage while getItem is used to get the item from the local/sessionStorage using the variable name.

localStorage.setItem("Name", "jQuery Pro");

use below statement to get the above value.

localStorage.getItem('Name');

 

sessionStorage

sessionStorage is same as localStorage only the difference is the validity of the variable or objects stored in this is temporary i.e. until the browser or tabs in closed. As soon as tab / browser is closed, data are lost. Data are never sent to server using this. Storage limit is lesser than localStorage which is 5 MB.

Same as in localStorage, get and set Item are used to get and set the value.

Watch out below video to understand and see live example of localStorage and sessionStorage.

Leave a Reply

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

Enjoy this blog? Please spread the word :)