SessionStorage.setItem JavaScript Example

SessionStorage.setItem() Method: Add key and value to SessionStorage.


The syntax for SAVING data to sessionStorage:
sessionStorage.setItem("key", "value");

sessionStorage.setItem() Method Example

This method just as the name implies allows you to store values in the sessionStorage object.
It takes two parameters, a key, and a value. The key can be referenced later to fetch the value attached to it.
sessionStorage.setItem("firstName", "Ramesh");
Where "firstName" is the key and "Ramesh" is the value. Also, note that unlike LocalStorage, the sessionStoragecan 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));
Note that the data is deleted when the browser tab is closed.