How to Use sessionStorage in JavaScript

Web Dev
Sponsored links

In this article, I will introduce how to use sessionStorage in JavaScript.

What is the sessionStorage?

The sessionStorage is like a storage area in your browser where you can store information for the duration of a web page session.

Information such as variables normally held by JavaScript is reset when the page is reloaded.
The sessionStorage allows you to retain information when you close a page, as long as you don't close the browser window or tab.

Sponsored links

How to use sessionStorage

The format of the data to be saved is a combination of key and value like a JavaScript object.

This time, I will explain three ways to use sessionStorage: "Set", "Get", and "Remove".

Set data in sessionStorage

To set the data, specify the key and value in the setItem method.

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

When executing the above code, if the specified key does not exist, it will be newly created, and if it already exists, it will overwrite the existing value.
Keep in mind that you can only specify a string as the data value for sessionStorage.

If you want to store multiple elements such as objects and arrays in sessionStorage, it is necessary to return the data stored as a character string to the objects and arrays after getting it.

Get data from sessionStorage

To get the data, specify the key of the data you want to get in the argument of getItem method.

sessionStorage.getItem('key')

Remove data from sessionStorage

Use the removeItem method to remove the data.

sessionStorage.removeItem('key')

Specify the key of the data you want to remove in the argument.

Sponsored links

Sample Code

Below is sample code to store an object and an array in sessionStorage.

// Sample1
const dataObj = {
  name: 'Plantpot',
  country: 'Japan'
};

// Convert an object to a string
const str1 = JSON.stringify(dataObj);

// Set data in sessionStorage
sessionStorage.setItem('profile', str1);

// Get data from sessionStorage
const profileStr = sessionStorage.getItem('profile');

// Convert a string to an object
const profileObj = JSON.parse(profileStr1);

console.log(profileObj);
//{
//  name: 'Plantpot',
//  country: 'Japan'
//}



// Sample2
const dataArr = ['Apple', 'Orange'];

// Convert an array to a string
const str2 = dataArr.join();

// Set data in sessionStorage
sessionStorage.setItem('fruits', str2);

// Get data from sessionStorage
const fruitsStr = sessionStorage.getItem('fruits');

// Convert a string to an array
const fruitsArr = fruitsStr.split(',');

console.log(fruitsArr);
// ['Apple', 'Orange']