0
0
JavascriptHow-ToBeginner · 4 min read

How to Use sessionStorage in JavaScript: Simple Guide

Use sessionStorage.setItem(key, value) to save data and sessionStorage.getItem(key) to retrieve it within the same browser tab session. Data stored in sessionStorage lasts only until the tab or window is closed.
📐

Syntax

sessionStorage is a built-in JavaScript object that stores data as key-value pairs for the duration of the page session.

  • sessionStorage.setItem(key, value): Saves a value under the specified key.
  • sessionStorage.getItem(key): Retrieves the value for the given key.
  • sessionStorage.removeItem(key): Deletes the key and its value.
  • sessionStorage.clear(): Clears all stored data in the session.
javascript
sessionStorage.setItem('username', 'Alice');
const user = sessionStorage.getItem('username');
sessionStorage.removeItem('username');
sessionStorage.clear();
💻

Example

This example shows how to save a user's name in sessionStorage, retrieve it, and display it on the page. The data will be lost when the browser tab is closed.

javascript
// Save data
sessionStorage.setItem('name', 'Alice');

// Retrieve data
const name = sessionStorage.getItem('name');

// Display data
if (name) {
  console.log('Hello, ' + name + '!');
} else {
  console.log('No name found in sessionStorage.');
}
Output
Hello, Alice!
⚠️

Common Pitfalls

Common mistakes when using sessionStorage include:

  • Trying to store objects directly without converting them to strings (use JSON.stringify() and JSON.parse()).
  • Expecting data to persist after closing the browser tab (it only lasts per tab session).
  • Not checking if sessionStorage is supported by the browser.
javascript
// Wrong way: storing an object directly
const user = { name: 'Alice' };
sessionStorage.setItem('user', user); // stores '[object Object]'

// Right way: convert object to string
sessionStorage.setItem('user', JSON.stringify(user));

// To retrieve and parse back
const storedUser = JSON.parse(sessionStorage.getItem('user'));
📊

Quick Reference

MethodDescription
setItem(key, value)Stores a value under the given key as a string.
getItem(key)Retrieves the string value for the given key or null if not found.
removeItem(key)Removes the key and its value from storage.
clear()Removes all keys and values from sessionStorage.
lengthReturns the number of stored items.
key(index)Returns the key at the given index.

Key Takeaways

Use sessionStorage to store data that lasts only during the browser tab session.
Always convert objects to strings with JSON.stringify before storing.
Data in sessionStorage is cleared when the tab or window is closed.
Check for browser support before using sessionStorage.
Use setItem, getItem, removeItem, and clear methods to manage sessionStorage data.