How to store objects in HTML5 localStorage?

In this tutorial, we will discuss how to store objects in HTML5 localStorage. We can access the Storage object and store data in it thanks to the interface window's localStorage property.

There is no time limit on it. As a result, the data that is stored in it will remain until it is explicitly deleted. The localStorage data can't be removed by closing the browser.

To store JavaScript objects in localStorage, we will investigate how to stringify and parse them into JSON strings and then how to store them in localStorage.

Using the setItem() Method

This setItem() method is used to store data in HTML5 localStorage. This method comes under the localStorage property of the window interface.

Syntax

window.localStorage.setItem(key, value);

Here, we have used two parameters in the method setItem(key, value). A key and Value. Let?s understand the parameters in detail.

Parameters

key ? This is a distinct identifier of a value. It is possible later to obtain a value from localStorage using this distinct identifier.

value ? This is the data/information that will be kept in localStorage.

Example 1

In this example, First, we are creating an object that we will store in localStorage named objectRegion. Afterward, we define two variables: a key and a value. Variable value contains the JSON format of the object. Then using setItem() we are setting this key and value pair to localStorage. Here we have also used the getItem() method, which will find value from the key provided. It returns the value corresponding to the key. Then we display it.


   

Add an Object to localStorage in HTML5 using setItem() method

Example 2

Here in this example, we can store an object in localStorage and retrieve it. We have the first two input text boxes through which we can store value to localStorage. And using the key, we can retrieve the value. If the key is not in localStorage, getItem () returns a null value.


   

Set the value to localStorage using setItem() method in an HTML5

Set the key-value pair to localStorage





Get the value from key



In this tutorial, We have seen how to store objects in HTML5 in localStorage using the setItem() method.

Updated on: 2022-12-06T12:34:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements