Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] JavaScript localStorage – Simple Guide with Example

#1
JavaScript localStorage – Simple Guide with Example

by Vincy. Last modified on August 21st, 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.

↑ Back to Top



https://www.sickgaming.net/blog/2022/08/...h-example/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] JavaScript – How to Open URL in New Tab xSicKxBot 0 16 12-03-2025, 02:57 AM
Last Post: xSicKxBot
  [Tut] JavaScript – How to Open URL in New Tab xSicKxBot 0 1,853 08-21-2023, 10:25 AM
Last Post: xSicKxBot
  [Tut] How to Wait 1 Second in JavaScript? xSicKxBot 0 1,458 10-19-2022, 03:08 AM
Last Post: xSicKxBot
  [Tut] AJAX Call in JavaScript with Example xSicKxBot 0 1,477 09-27-2022, 10:19 AM
Last Post: xSicKxBot
  [Tut] JavaScript this Keyword xSicKxBot 0 1,437 09-14-2022, 02:01 PM
Last Post: xSicKxBot
  [Tut] JavaScript News Ticker xSicKxBot 0 1,257 08-29-2022, 08:37 AM
Last Post: xSicKxBot
  [Tut] Generate PDF from HTML with JavaScript and Example xSicKxBot 0 1,467 05-13-2022, 10:43 AM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016