LOCAL STORAGE AND SESSION STORAGE

LOCAL STORAGE AND SESSION STORAGE

SessionStorage and LocalStorage are known as the web storage API. Data can be stored in the browser by using these APIs.

SessionStorage:

SessionStorage is used for storing data on the client-side. The maximum limit of data saving in SessionStorage is about 5MB - 10MB depending on the browser. Data in the SessionStorage exist till the current tab is open if we close the current tab then our data will also erase automatically from the SessionStorage.

LocalStorage:

Like SessionStorage, LocalStorage also used for storing the data on the client-side. The maximum limit of data saving is about 5MB - 10MB in LocalStorage also.= depending on the browser. LocalStorage has no expiration time, data in the LocalStorage persist until the user manually deletes it. This is the only difference between LocalStorage and SessionStorage

LocalStorage and SesionStoarage are both object types and in order to store data in, the data must be stored in a key-value pair and the key-value pair must either be a number or string

Methods in LocalStorage and SessionStorage:

  • For storing data in web storage:
LocalStorage.setItem("key", "value");  //key and value both should be string or number;
SessionStorage.setItem("key", "value");  //key and value both should be string or number;
  • For getting data from web storage
LocalStorage.getItem("key");
SessionStorage.getItem("key");

Here we will pass the key and it will return value.
  • For getting the length of web storage objects
LocalStorage.length; 
SessionStorage.length;
  • For deleting a particular key-value pair
LocalStorage.removeItem("key");
SessionStorage.removeItem("key");

when we pass key in method,
it will erase the complete data related to that key.
  • For clearing the storage completely
LocalStorage.removeItem("key");
SessionStorage.removeItem("key");

when we pass key in method,
it will erase the complete data related to that key.
  • Storing JSON Objects Only strings can be stored with localStorage or sessionStorage, but you can use JSON.stringify to store more objects and JSON.parse to parse them:
//storing the object
let obj = { name:'Maria' , age: 12};
localStorage.setItem(key, JSON.stringify(myObj));

// parsing the item:
let myObj = JSON.parse(localStorage.getItem(key));

Note:

Web storage is not a secured storage. it is advised never to store sensitive information in web storage as it always stores the data in the plain text format, anyone can steal the data easily. So do not store sensitive information such as passwords, payment details, etc with web storage.

Further readings

  1. javascript.info/localstorage
  2. developer.mozilla.org
  3. w3schools.com