JavaScript localStorage – Simple Guide with Example

by Vincy. Last modified on August 22nd, 2022.

This article is for learning how to use JavaScript localStorage to put a string or object into it. This is for storing data in the client browser and use it when the need arises.

Data storage is a critical part of programming. These are the scenarios the localStorage used for adding persistency on the client-side.

  1. To store the session and the unique identity of a guest user to manage the state of his selection.
  2. To store shopping cart selected items on the client-side.
  3. To store language preferences to display content on a multilingual site.
  4. To store user preferences to display data, time and timezone as selected on the client.

Let us see a quick example of using the JavaScript localStorage to store an object. It prepares a JSON object of an array of data and put it into the localStorage.

Quick example

var animalObject = {
	'Lion': 'Wild',
	'Dog': 'Domestic'
};

// flatten the animal object as a string
animalString = JSON.stringify(animalObject);

//store the string into local storage
localStorage.setItem('animals', animalString);

Quick example output

Log this localStorage object into the developer’s browser console to display the following output.

Object from local storage: {Lion: 'Wild', Dog: 'Domestic'}

In a previous tutorial, we used JavaScript localStorage to create a persistent shopping cart.

javascript localstorage howto store object

What is localStorage?

The JavaScript localStorage is the global window object property. It is used to store the data to carry over page-to-page.

It is one of the storage mechanisms coming under the Web Storage API.

It can not replace the server-side solutions providing persistency. But, it is a good mechanism for non-dynamic websites.

It contains a handle to access the local storage space of the browser origin.

Properties

Web Storage API

Web Storage API provides two concepts to store the objects having data in a key: value format.

  1. window.localStorage
  2. window.sessionStorage

Both use different Storage instances and control the actions separately.

This storage object is similar to the JavaScript localStorage. But, it has an expiration time.

It is valid only on the current browser session. When closing and reloading the browser, then the sessionStorage object is elapsed.

The expiration time is the main difference between these two storage concepts.

How to set and get items in JavaScript localStorage?

This example is for learning a basic usage of the JavaScript localStorage object. It performs the following actions on the localStorage about a String item.

  1. To set an item as a key-value pair.
  2. To get the value of an item by key.
  3. To remove an item by key.
  4. To clear the entire localStorage.
  5. To get the key by item index position.

This localStorage class contains functions used to perform the above actions. This program uses these functions with appropriate parameters.

basics.html

<html>
<head>
<title>JavaScript localStorage Example and how to store a
    JavaScript object</title>
</head>
<body>
    <script>
	// set item in localstorage
	window.localStorage.setItem('king', 'Lion');
	console.log("Local Storage Key-Value = " + JSON.stringify(window.localStorage) + "\n");

	// get item from JavaScript localStorage
	window.localStorage.getItem('king');
	console.log("Local Storage Value = " + window.localStorage.getItem('king') + "\n");

	// to get name of key using index
	var indexPosition = parseInt(window.localStorage.length) -1;
	var KeyName = window.localStorage.key(indexPosition);
	console.log("Local Storage Key = " + KeyName + "\n");

	// remove item from JavaScript localStorage
	window.localStorage.removeItem('king');

	// to clear all items from localStorage
	window.localStorage.clear();
    </script>
</body>
</html>

Output

The above program displays the following output. It is for printing the localStorage data, it’s key and value based on the appropriate function calls.

Local Storage Key-Value = {"king":"Lion"}

Local Storage Value = Lion

Local Storage Key = king

Store JavaScript object in HTML5 browser localStorage

This example is to store an object in the JavaScript localStorage. It proceeds with the following steps to achieve this.

  1. It builds a JSON object to have a property array.
  2. It converts the object into a string using JSON stringify.
  3. Then put the JSON string into the localStorage.

Like the above basic example, it calls the getItem() by object key to get the property mapping.

The retrieved string output from the localStorage is converted back to an object. The example outputs the converted object to the browser console.

index.html

<html>
<head>
<title>JavaScript localStorage Example and how to store a
    JavaScript object</title>
</head>
<body>
    <h1>JavaScript localStorage Example and how to store a
        JavaScript object</h1>
    <script>
		// Example: Store JavaScript object in HTML5 browser localStorage
		var animalObject = {
			'Lion' : 'Wild',
			'Dog' : 'Domestic',
			'Tiger' : 'Wild'
		};

		// flatten the object as a string
		animalString = JSON.stringify(animalObject);

		//store the string into local storage
		localStorage.setItem('animals', animalString);

		//retrieve the string from local storage
		var retrievedString = localStorage.getItem('animals');

		// parse the string back to an object
		convertedObject = JSON.parse(retrievedString);

		console.log('Object from local storage: ', convertedObject);
	</script>
</body>
</html>

Output

Object from local storage: 
{Lion: 'Wild', Dog: 'Domestic', Tiger: 'Wild'}

We learned how to use JavaScript localStorage to set a String or an Object and use it later when needed.
Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “JavaScript localStorage – Simple Guide with Example”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page