How to Set Session Variable in JavaScript

Mehvish Ashiq Feb 02, 2024
  1. localStorage vs sessionStorage in JavaScript
  2. Set Variable in localStorage and sessionStorage Using JavaScript
How to Set Session Variable in JavaScript

Our motive is to learn about sessions and set session variables in JavaScript. A session is a part of server-side storage where the data is stored and accessed depending on the unique id of each user.

For instance, whenever the user interacts with the website, it creates a new session object for that particular user and assigns them a cookie.

This cookie is checked whenever the user request from the exact client again and sent to the server for further processing and updating the session information that is already stored. The sessions get cleared as soon as the user clears the cookies.

You may have a question why is it important to use sessions?

The stateless HTTP protocol does not track any information about responses & requests, which means there is no relation among multiple requests by the one user (same user). The sessions are used to solve this issue.

For example, we have a form with multiple pages. Page 1, Page 2, and Page 3 are about personal information, education details, and family information, respectively.

The application can only be submitted once the user fills all three pages. In this scenario, we may need to store the submitted data from Page 1&2 into a session.

Once the user submits Page 3, we can get that page 3 from the HTTP request and the remaining Page 1&2 from the session. It is how sessions are used.

Now we understand sessions and know that the server maintains them. It is impossible to assign session values directly using JavaScript, but we (as web developers) want to use session storage locally to save, retrieve, update data.

We can use localStorage and sessionStorage.

localStorage vs sessionStorage in JavaScript

The localStorage object allows storing data in key-value pairs in the browser with no expiration. Even after closing the tab or browser, the data can be used for upcoming sessions (future sessions).

The sessionStorage object is similar to localStorage, but it stores data only for one session. The data is lost when the tab/browser is closed or refreshed.

Following is a brief comparison among both of these, but you can find more about it here.

Local Storage Session Storage
Capacity 10 MB 5 MB
Browsers HTML 5 HTML 5
Accessible From Any Window Same Tab
Expires Never On Tab Close
Storage Location Browser Only Browser Only
Sent With Requests No No

Set Variable in localStorage and sessionStorage Using JavaScript

The methods are the same for storing and retrieving data in localStorage and sessionStorage. These methods are listed below.

  1. setItem(key, value) stores key-value pairs.
  2. getItem(key) retrieves the value via key.
  3. removeItem(key) removes both the key and value.
  4. clear() deletes the entire storage and clears everything.
  5. key(index) returns the key on a particular position.
  6. length tells the number of stored items.

Never use these storage mechanisms to store confidential information.

JavaScript Code to Practice For localStorage:

localStorage.setItem('fname', 'Bob');
localStorage.setItem('lname', 'Thomas');

console.log(localStorage.getItem('fname'));
console.log(localStorage.getItem('lname'));

// returns null
console.log(localStorage.getItem('firstname'));

// removes the item with key and value
localStorage.removeItem('fname');
// clears the entire storage
localStorage.clear()

Output:

javascript set session variable - localStorage

JavaScript Code to Practice For sessionStorage:

sessionStorage.setItem('fname', 'Bob');
sessionStorage.setItem('lname', 'Thomas');

console.log(sessionStorage.getItem('fname'));
console.log(sessionStorage.getItem('lname'));

// returns null
console.log(sessionStorage.getItem('firstname'));

// removes the item with key and value
sessionStorage.removeItem('fname');
// clears the entire storage
sessionStorage.clear()

Output:

javascript set session variable - sessionStorage

Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook

Related Article - JavaScript Variable