SessionStorage.removeItem JavaScript Example

SessionStorage.removeItem(): Remove an item by key from SessionStorage.

Syntax

window.sessionStorage
The syntax for SAVING data to sessionStorage:
sessionStorage.setItem("key", "value");
The syntax for READING data from sessionStorage:
var lastname = sessionStorage.getItem("key");
The syntax for REMOVING saved data from sessionStorage:
sessionStorage.removeItem("key");

sessionStorage.removeItem() Method Example

First, we add a key and value pair to sessionStorage.

sessionStorage.setItem("firstName", "Ramesh");
Where "firstName" is the key and "Ramesh" is the value. Also, note that sessionStorage can only store strings.
To store arrays or objects you would have to convert them to strings.
To do this we use the JSON.stringify() method before passing to setItem() .
var user = {
 firstName : "Ramesh",
 lastName : "Fadatare"
}
sessionStorage.setItem("id", JSON.stringify(user));
Now, let's use the removeItem() method to remove the item from the key. Let's remove the user object previously stored using setItem() method:
sessionStorage.removeItem('id');
Similarly, remove "Ramesh" value from storage.
sessionStorage.removeItem("firstName");

Reference


Comments