How to access and set Session Variables in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 7, 2024
4 min

banner

# Table of Contents

  1. How to access and set Session Variables in JavaScript
  2. sessionStorage vs localStorage in JavaScript
  3. Using the localStorage property to access and set variables

# How to access and set Session Variables in JavaScript

You can use sessionStorage.setItem() and the sessionStorage.getItem() method to access and set session variables in JavaScript.

The sessionStorage API enables you to store and access data saved in the current page session.

Here is the HTML for the example. It simply loads a JS script.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="id">bobbyhadz.com</div> <script type="module" src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
/** * Setting session variables */ sessionStorage.setItem('first', 'bobby'); sessionStorage.setItem('last', 'hadz'); const arr = ['dev', 'test', 'ship']; sessionStorage.setItem('tasks', JSON.stringify(arr)); // ----------------------------------- /** * Accessing session variables */ console.log(sessionStorage.getItem('first')); // ๐Ÿ‘‰๏ธ bobby console.log(sessionStorage.getItem('last')); // ๐Ÿ‘‰๏ธ hadz const parsed = JSON.parse(sessionStorage.getItem('tasks')); console.log(parsed); // ๐Ÿ‘‰๏ธ ['dev', 'test', 'ship']

access set session variables

The code for this article is available on GitHub

The sessionStorage property is used to access a session Storage object for the current origin.

The setItem() method takes 2 parameters - a key and a value and sets the key-value pair on the Storage object.

Note that the key and the value have to be strings.

If you need to store an array or an object, make sure to use the JSON.stringify() method to convert the value to a string before storing it in sessionStorage.

index.js
sessionStorage.setItem('tasks', JSON.stringify(arr));

The getItem() method takes a key as a parameter and returns the corresponding value.

If you previously stored a JSON string, make sure to use the JSON.parse() method to parse the value back to a native JavaScript object.

index.js
sessionStorage.setItem('tasks', JSON.stringify(arr)); console.log(sessionStorage.getItem('first')); // ๐Ÿ‘‰๏ธ bobby

You can open the Console tab in your developer tools to look at the output of calling the sessionStorage.getItem() method.

# sessionStorage vs localStorage in JavaScript

There are 2 very similar APIs that allow you to access the Storage object:

The main difference between the two is that:

  • Data stored using sessionStorage is only valid for the particular Tab. When the tab is closed, the data is cleared.
  • Conversely, localStorage has no expiration and is not cleared when the Tab is closed.
When you open multiple tabs/windows with the same URL, a unique sessionStorage property is created for each tab/window.

On the other hand, the localStorage property is shared by all tabs/windows with the same URL.

You can view your localStorage and sessionStorage variables by opening your developer tools (F12) and selecting the Application tab.

open developer tools click application

You can expand the Local Storage or Session Storage dropdown menus in the left sidebar.

Each menu shows the currently stored key-value pairs.

To better understand the difference between session storage and local storage:

  1. Run the following code in your browser.
index.js
/** * Setting session variables */ sessionStorage.setItem('first', 'bobby'); sessionStorage.setItem('last', 'hadz'); const arr = ['dev', 'test', 'ship']; sessionStorage.setItem('tasks', JSON.stringify(arr)); // ----------------------------------- /** * Accessing session variables */ console.log(sessionStorage.getItem('first')); // ๐Ÿ‘‰๏ธ bobby console.log(sessionStorage.getItem('last')); // ๐Ÿ‘‰๏ธ hadz const parsed = JSON.parse(sessionStorage.getItem('tasks')); console.log(parsed); // ๐Ÿ‘‰๏ธ ['dev', 'test', 'ship']
The code for this article is available on GitHub
  1. If you open the Application tab in your developer tools and click on Session Storage, you will see that the key-value pairs have been set.

session storage key value pairs set

  1. Now comment out the code or remove it.

  2. Close the browser tab and reopen it.

  3. If you open the Application tab in your developer tools and click on Session storage, you will see that the key-value pairs have been removed.

session storage key value pairs removed

Data stored using sessionStorage is only valid for the particular Tab. When the tab is closed, the data is cleared.

# Using the localStorage property to access and set variables

Let's look at an example of using the localStorage property to access and set variables that are saved across browser sessions.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="id">bobbyhadz.com</div> <script type="module" src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
/** * Setting variables that are saved across browser sessions */ localStorage.setItem('first', 'bobby'); localStorage.setItem('last', 'hadz'); const arr = ['dev', 'test', 'ship']; localStorage.setItem('tasks', JSON.stringify(arr)); // ----------------------------------- /** * Accessing the variables */ console.log(localStorage.getItem('first')); // ๐Ÿ‘‰๏ธ bobby console.log(localStorage.getItem('last')); // ๐Ÿ‘‰๏ธ hadz const parsed = JSON.parse(localStorage.getItem('tasks')); console.log(parsed); // ๐Ÿ‘‰๏ธ ['dev', 'test', 'ship']
The code for this article is available on GitHub

If I open the Console tab, I can see that the values are logged to the console.

localstorage values logged to console

You can also click on the Application tab and select Local Storage in the left sidebar.

select application local storage

As with the sessionStorage API, the setItem() method takes 2 strings - a key and a value.

If you need to store an array or an object in localStorage, make sure to stringify it.

index.js
localStorage.setItem('tasks', JSON.stringify(arr));

When you need to retrieve the data, make sure to parse it to a native JavaScript object.

index.js
const parsed = JSON.parse(localStorage.getItem('tasks'));

The benefit of using localStorage is that the data is preserved after you close the tab.

To better illustrate how this works:

  1. Run the following code in your browser.
index.js
/** * Setting variables that are saved across browser sessions */ localStorage.setItem('first', 'bobby'); localStorage.setItem('last', 'hadz'); const arr = ['dev', 'test', 'ship']; localStorage.setItem('tasks', JSON.stringify(arr)); // ----------------------------------- /** * Accessing the variables */ console.log(localStorage.getItem('first')); // ๐Ÿ‘‰๏ธ bobby console.log(localStorage.getItem('last')); // ๐Ÿ‘‰๏ธ hadz const parsed = JSON.parse(localStorage.getItem('tasks')); console.log(parsed); // ๐Ÿ‘‰๏ธ ['dev', 'test', 'ship']
The code for this article is available on GitHub
  1. If you open the Application tab in your developer tools and click on Local Storage, you will see that the key-value pairs have been set.

select application local storage

  1. Now comment out the code or remove it.

  2. Close the browser tab and reopen it.

  3. If you open the Application tab in your developer tools and click on Local storage, you will see that the key-value pairs persist between sessions.

key value pairs persist between sessions

This is because localStorage has no expiration and is not cleared when the Tab/Window is closed.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev