JavaScript Tools: localStorage and sessionStorage

JavaScript (often abbreviated as JS) is one of the foundations of the modern web infrastructure. It’s a lightweight, interpreted, object-oriented programming language that supports first-class functions. JavaScript is mostly known for its implementation in dynamic web pages. Because of its features, however, JavaScript is also used in non-browser environments.

In this guide, we will discuss in detail two JavaScript objects: localStorage and sessionStorage.

localStorage and sessionStorage Overview

The objects localStorage and sessionStorage are offered as a part of the web storage API. It’s a great tool for local storage of key-value pairs. Using localStorage and sessionStorage is a great alternative to cookies. This approach offers some extra benefits:

  • Data is stored locally and can’t be read by the server. This eliminates the security issues with cookies.
  • It allows higher storage capacity (up to 10 MB for most modern browsers).
  • Simple and straightforward syntax.

These objects are supported on all modern web browsers, so there won’t be an issue with browser compatibility. Cookies are still useful in many situations, for example, authentication. However, there are situations where localStorage and sessionStorage offer better solutions.

Prerequisites

To perform the steps shown in this tutorial, you’ll need the following components:

For demonstration, we grabbed a sample web page attached with a JS script. You can learn more about adding JavaScript to an HTML file here:

tree_struct

VS 1

As for the text editor, we will be using Visual Studio Code:

Web 1

What is the Difference between localStorage and sessionStorage?

Both localStorage and sessionStorage originate from the same API. Their behaviors are also identical. The only difference is in the way that each object allows data persistence. In the case of sessionStorage, the data persists until the window or tab is closed. With localStorage, the data persists until the browser cache is cleared or the web app clears it.

In this tutorial, we’ll mostly focus on localStorage. However, the syntax for sessionStorage is the same. We’ll showcase how to create, read, and update key/value pairs using localStorage.

Step 1 – Creating Entries

We can declare an entry to the localStorage object using setItem(). This method takes two arguments: the key and its corresponding value. The method structure is as follows:

In the following example, we created a variable key. Using the setItem() method, we have set a new key and set its value to value:

VS 2

Step 2 – Reading Entries

Now, how do we read the value stored in the key? To get a key from localStorage, we’ll use the method getItem(). It takes the name of the key and returns the values stored in the key. We’ll use the alert() method to display the content we fetch:

VS 3

Next, open the webpage in a web browser. It should show the value stored in the key:

Web 2

Step 3 – Updating Entries

Once a value is set, it will remain so unless it’s changed. If we use the setItem() method on the same key again, it will automatically replace the old value with the new one.

In the following example, the key is first initiated with the value value. In the next line, we have called setItem() once again and set the value to new value:

VS 4

Let’s see what happens when we run this code in the browser:

Web 3

As we can see, the value of the key is set to new value.

Step 4 – Deleting Entries

If there are multiple entries in the localStorage (and sessionStorage as well) that are no longer necessary, it’s recommended to clear them afterward. This opens up more space for later use. The app also becomes more memory efficient.

To delete an entry from localStorage, there is a dedicated method removeItem(). It takes the key as an argument and removes it from the localStorage data pool:

Let’s implement it in our script:

VS 5

When run, the output says null because there exists no value for the key:

Web 4

Step 5 – Clearing Entries

In the previous example, we removed only one key. However, localStorage allows clearing all the items stored in a single step. To clear all the entries, localStorage offers the method clear(). It takes no argument:

Put the method in action:

VS 6

Just like before, it removes all the entries from localStorage, so when trying to access the key value, it returns null:

Web 5

Step 6 – Working with JSON

  • Storing Objects and Arrays

The localStorage and sessionStorage objects can only store string values. However, there will be times when you have to work with objects or arrays. In that case, we need to convert them into a string.

JavaScript comes with the feature JSON.stringify() that will take the array/object and convert it into strings. This post gives a quick overview of the JSON format. For a more elaborated guide, you can read JSON in JavaScript.

In this example, we created an object sampleObj with two fields name and location. We’ll convert it into a string and store it in the key:

VS 7

Here, the output will be the string containing the data of the object:

Web 6

  • Reading Objects and Arrays

When storing, we converted objects and arrays into strings. We can take this string and convert it back to its original format as well. To do so, we’ll be using the method JSON.parse(). It takes a string and converts it back into JSON format:

VS 8

As for the output, we re-converted it into a string and formatted it for a better view:

Web 7

Step 7 – Checking for Item in localStorage

In this section, we’ll showcase a simple test to determine if localStorage and sessionStorage contain any item or not. Using a simple if statement, we can check the length of localStorage or sessionStorage. If there are items, the length will be greater than 0.

First, implement the following example:

VS 9

Here, the output will be true because there exists one key in localStorage:

Web 8

Step 8 – Iterating Over Items

The localStorage and sessionStorage object stores the keys in an array-like structure. They don’t support the forEach method, so we’ll have to follow the classic technique of using a for loop to iterate over each item.

In the following example, we’ll check if localStorage is empty or not. If not empty, then we’ll iterate over each item:

VS 10

The output will show all the items one by one:

Web 9

Step 9 – Check Browser Support

We can check support for localStorage (and sessionStorage) by checking if it’s available on the window object. A simple if statement will do the trick:

VS 11

Run the code in the web browser:

Web 10

Final Thoughts

This guide demonstrated how to use localStorage and sessionStorage objects in JavaScript to store key/value pairs in the browser. The syntaxes are much simpler to work with. We showcased how to create, remove, and update key/value pairs. We also tackled storing objects and arrays by converting them into strings (and vice-versa).

To further deepen your knowledge of JavaScript, you can check out the following tutorials from our blog:

Happy Computing!