Difference between localStorage and sessionStorage?

Home >> Blog >> Difference between localStorage and sessionStorage?

What is the difference between localStorage and sessionStorage?
Q:- What is localStorage and sessionStorage? Why we use it?

Web Storage objects i.e. - Storage

localStorage and sessionStorage provides us facility to store data locally within the user's browser in key/value pair in string format.

localStorage vs sessionStorage

Key Points:

localStorage and sessionStorage both can be differentiated using the following key points.

  1. Storage Lcoation – Both are available client-side only.
  2. Capicity – Default size is 5MB. (vary on some browsers)
  3. Expire Time – localStorage - Never, sessionStorage - On browser's tab close.
  4. Accessiblilty – localStorage - From any window/tab, sessionStorage - In same tab only.
  5. Browsers Support – HTML5 only.
Methods and Properties:

localStorage and sessionStorage both provides same methods and properties.

  1. setItem(key, value) – store item as key/value pair in string format.
  2. getItem(key) – get item's value by using key.
  3. removeItem(key) – remove an item using key.
  4. clear() – clear or delete everything.
  5. length – returns total number of stored items.
Q:- How to check browser support localStorage and sessionStorage?

Let's check browser support for localStorage and sessionStorage.

if (typeof Storage !== "undefined") { console.log("Congrats!, browser supports localStorage and sessionStorage."); } else { console.log( "Sorry!, browser does not supports localStorage and sessionStorage." ); }
Examples - localStorage and sessionStorage?
// Save data to localStorage localStorage.setItem('key', 'value'); // Get saved data from localStorage let data = localStorage.getItem('key'); // Remove saved data from localStorage localStorage.removeItem('key'); // Remove all saved data from localStorage localStorage.clear();
// Save data to sessionStorage sessionStorage.setItem('key', 'value'); // Get saved data from sessionStorage let data = sessionStorage.getItem('key'); // Remove saved data from sessionStorage sessionStorage.removeItem('key'); // Remove all saved data from sessionStorage sessionStorage.clear();
Q:- Can we store JSON Object into localStorage and sessionStorage?

Yes, You can store it after converting object into string by using JSON.stringify().

let myObj = { 'name': "Full Stack Tutorials", 'age': 30 }; // Save the object into localStorage localStorage.setItem('myObj', JSON.stringify(myObj)); // Get the object from localStorage let getObj = localStorage.getItem('myObj'); console.log(JSON.parse(getObj));