LocalStorage and SessionStorage in JavaScript

How to Store Data in Web Browser Storage – localStorage and sessionStorage.

The main difference between sessionStorage and localStorage is that sessionStorage only maintains a storage area while the browser is open (including when the page reloads or restores) while localStorage continues to store data after the browser is closed. In other words, whereas data stored in sessionStorage is cleared when the page is closed, data stored in localStorage does not expire.

  1. setItem(key, value) – Add key and value to sessionStorage or localStorage.
  2. getItem(key) – This is how you get items from sessionStorage or localStorage.
  3. removeItem(key) – remove the key with its value from sessionStorage or localStorage.
  4. clear() – Clear all from sessionStorage or localStorage.
  5. key(index) – Passed a number to retrieve the key of a sessionStorage or localStorage.
  6. length – The number of stored items.
To save an item value to localStorage or sessionStorage.
localStorage.setItem("Order_id","12345");
or
sessionStorage.setItem("first_name","Vikas");
To get an item value from localStorage or sessionStorage.
localStorage.getItem("Order_id");
or
sessionStorage.getItem("first_name");
To Remove an item with its value from localStorage or sessionStorage.
localStorage.removeItem("Order_id");
or
sessionStorage.removeItem("first_name");
To clear everything from localStorage or sessionStorage.
localStorage.clear();
or
sessionStorage.clear();
To Check the storage name using index from localStorage or sessionStorage.
localStorage.key(0);
localStorage.key(1);
or
sessionStorage.key(0);
sessionStorage.key(1);
To get the no of storage in localStorage or sessionStorage.
localStorage.length;
or
sessionStorage.length;