Learn about SessionStorage in JavaScript.
2 min readMay 29, 2023
What is sessionStorage?
SessionStorage
is a global object that allows you to store data in the browser’s local storage. The data is stored in a key-value pair format, and it is only available to the current session.
This means that when you close the browser, the data is deleted.
How to use sessionStorage
To use sessionStorage, you can use the following methods:
setItem()
: This method is used to set a key-value pair in sessionStorage.getItem()
: This method is used to get the value of a key insessionStorage
.removeItem()
: This method is used to remove a key fromsessionStorage
.clear()
: This method is used to clear all of the data fromsessionStorage
.
Example
The following code shows how to use sessionStorage to store a user’s name:
Code snippet
// Set the user's name
sessionStorage.setItem("name", "Rajini");
// Get the user's name
const name = sessionStorage.getItem("name"); // Rajini
// Remove the user's name
sessionStorage.removeItem("name");
// Clear all of the data
sessionStorage.clear();