Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

sessionStorage

sessionStorage is another type of client-side storage provided by modern browsers. Similar to localStorage, it allows web applications to store data locally on a user's device. However, sessionStorage differs in that it provides temporary storage that is cleared once the browser session ends, i.e., when the browser tab or window is closed.

Examples

Storing Data:

sessionStorage.setItem('key', 'value');

This code snippet stores a key-value pair ('key' as the key and 'value' as the corresponding value) in the sessionStorage of the browser. The data will be available only for the duration of the browser session.

Retrieving Data

const data = sessionStorage.getItem('key');

This code retrieves the value associated with the key 'key' from the sessionStorage and stores it in the variable 'data'. It allows you to access previously stored data from sessionStorage within the current browser session.

Removing Data:

sessionStorage.removeItem('key');

This code removes the key-value pair with the key 'key' from the sessionStorage. After execution, the data associated with the specified key will no longer be available in the sessionStorage.

Clearing All Data:

sessionStorage.clear();

This code clears all the data stored in the sessionStorage of the browser. It removes all key-value pairs, effectively resetting the sessionStorage to an empty state, but only for the current browser session.

Use Cases

sessionStorage offers various use cases in web applications:

  • Managing temporary session-related data, such as shopping cart items.
  • Preserving state during multi-step processes, like form submissions.
  • Providing transient data storage for tasks that require data persistence within a single browser session.

Limitations

Despite its usefulness, sessionStorage has limitations similar to localStorage:

  • Limited storage capacity, typically around 5MB per origin.
  • Scoped to the current browser session, making data inaccessible across different sessions or browser tabs/windows.
  • Not suitable for storing sensitive information without encryption due to potential security risks.