Difference between localStorage and sessionStorage?

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

localStorage vs sessionStorage - difference between localStorage and sessionStorage
Q:- What is the Web Storage API?

In HTML5, Web Storage API provides mechanisms by which browser can store data in key/value format as strings.

Type of Web Storage API

  • localStorage
  • sessionStorage
Let's see some key difference between localStorage and sessionStorage.

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

Key Point localStorage sessionStorage
Storage Location Client-side - (In Browser) Client-side - (In Browser)
Data Capicity 5-10MB (depends on browser) 5MB (default)
Expiration Never Expire on Tab close
Accessiblilty From any Window/Tab Within same Tab only
Browser's Support HTML5 only HTML5 only
Sent with HTTP Requests No No
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.
Examples - localStorage
// 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();
Examples - sessionStorage
// 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();
Some Inportant questions related to localStorage and sessionStorage?
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!, the browser support localStorage and sessionStorage."); } else { console.log( "Sorry!, the browser does not support localStorage and sessionStorage." ); }
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));