Learn about SessionStorage in JavaScript.
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();
Limitations
There are a few limitations to sessionStorage:
- The maximum size of data that can be stored in
sessionStorage
is5MB
. - The data in
sessionStorage
is not shared between different tabs or windows. - The data in
sessionStorage
is not accessible to other websites.
Use cases
SessionStorage can be used for a variety of purposes, such as:
- Storing the user’s language preference
- Storing the user’s login status
- Storing the user’s shopping cart contents
- Storing the user’s progress in a game
Conclusion
SessionStorage
is a powerful tool that can be used to store data in the browser’s local storage. The data is only available to the current session, which means that it is not accessible to other websites or tabs. This makes sessionStorage
a secure way to store data.