How to store objects in HTML5 localStorage

Overview

The localStorage property of the interface window allows us to access the Storage object and store data in it.

It doesn't have an expiration time. Therefore, the data stored in it will persist until explicitly removed. Even closing the browser won't remove the localStorage data.

To use the localStorage in a web application, there are a couple of methods to store, retrieve, clear, and remove data. Out of them, we'll explore the setItem() method in this shot.

The setItem() method

As the name signifies, the setItem() method is used to store data in the HTML5 localStorage.

Syntax

window.localStorage.setItem(key, value);
The syntax of the setItem() method

Parameters

  • key: This is a unique identifier that can be used later to retrieve a value from localStorage.
  • value: This is the data to be stored in the localStorage.

Storing an object in localStorage

The values that are stored in the localStorage should be of the string datatype. To store an object or an array in the localStorage, we first need to convert it to string using the JSON.stringify() method. Next, we can pass it as the value in the setItem() method.

Example

Explanation

  • Lines 2–5: We create an object, myCountryInfo.
  • Line 9: We make the myCountryInfo object into a string and use the setItem() method to store it in the localStorage.
  • Line 12: We retrieve the localStorage data.

Free Resources