JavaScript - how to use sessionStorage
In this article, we would like to show you how to use sessionStorage in JavaScript.
1. Overview
TheĀ sessionStorage
Ā only works for the duration of the session. After the session ends, its storage is deleted.
The sessionStorage extends Storage that can store key/value (property/value) pairs and has built-in methods (like .length
, .key( )
, etc.).
2. View sessionStorage in web browser (Google Chrome)
In order to view items stored in the sessionStorage:
- Open developer tools (
F12
orCtrl
+Shift
+I
), - Go to the Application tab,
- from the Storage section in the menu on the left select Session Storage.
Now you can view sites and items they store in the sessionStorage.
Example view on items stored by dirask:

3. store value in sessionStorage
To put items into the sessionStorage we use setItem()
method that takes two arguments: key and value.
// ONLINE-RUNNER:browser;
window.sessionStorage.setItem('itemKey', 'itemValue');
Now you can see the item in the developer tools:

To store arrays or objects, you haveĀ to convert them to strings.
// ONLINE-RUNNER:browser;
const item = {
key: 'itemKey',
value: 'itemValue',
}
window.sessionStorage.setItem('item', JSON.stringify(item));
4. get itemĀ from sessionStorage
To get items from sessionStorage, we use getItem()
method that takes the item key (name) as an argument.
// ONLINE-RUNNER:browser;
var item = window.sessionStorage.getItem('itemKey');
console.log(item); // Output: itemValue
To get an object created converted to string withĀ JSON.stringify()
, you need to parse it back using JSON.parse()
method.
// ONLINE-RUNNER:browser;
var item = window.sessionStorage.getItem('item');
console.log(item); // Output: {"key":"itemKey","value":"itemValue"}
5. remove itemĀ from sessionStorage
To remove items fromĀ sessionStorage, we use removeItem()
method that takes the item key as an argument andĀ removes that key from the storage if it exists. If there is no item with the given key, theĀ method will do nothing.
// ONLINE-RUNNER:browser;
window.sessionStorage.removeItem('itemKey');
6. clear sessionStorage
To clear the entire sessionStorage, we use clear()
method that takes no arguments and clears the entire storage of all records for theĀ domain.
// ONLINE-RUNNER:browser;
window.sessionStorage.clear();
Ā