What is sessionStorage in JavaScript?
Overview
We use the sessionStorage object to save the key-value pairs for a specific session. The key and value should be strings. The value will only be available until the browser tab is open. If the user closes the tab, the data will be cleared.
- A new session is created when a browser tab is opened. The data will be available between the page refresh. When we close the tab, the session will end. The data is available, including iframes, from the same origin in the current tab.
- If we open the same URL in multiple tabs, each tab will have a separate session.
- The session data will be copied to the duplicated page when we duplicate the browser tab.
Here are the available methods:
-
setItem(key, value): This adds key-value pair tosessionStorage. getItem(key): This gets the value of the key.removeItem(key): This removes the key-value pair.clear(): This deletes all key-value pairs.key(index): This gets the key number index.length: This is the number of key-value pairs present.
Example
The code below demonstrates how to use sessionStorage:
Explanation
- Lines 7 and 8: We use the
setItem()method of thesessionStorageobject to add two entries to the object.
- Line 15: We use the
getItem()method of thesessionStorageobject to get the value associated with thenamekey.
- Line 18: We use the
removeItem()method of thesessionStorageobject to remove the entry with thenamekey.
- Line 23: We use the
clear()method of thesessionStorageobject to remove all data.