JavaScript Local Storage

 

localstorage

Definition and Usage

The setItem() method
sets the value of the specified Storage Object item.

The setItem() method belongs to the Storage Object,
which can be either a localStorage object or a sessionStorage object.

Main methods in local storage

The primary methods when using local storage are ...
key()
setItem()
removeItem(),
 getItem(), and 
clear().

key()

This method is used to retrieve a value/string from a specific location. The index can be passed into the key() function as a parameter.

var answer = localStorage.key(1);

The key() can also be used in a loop statement to retrieve all the items in the local storage.

setItem()

This function is used to store items in local storage. An example of this function is shown below.

window.localStorage.setItem("grade","One");
//in this case, the `grade` is the key while `One` is the value.

As mentioned before, we must stringify objects before we store them in the local storage.
An example is outlined below:

const Car = {
  brand:"Suzuki",
  color:"white",
  price:10000
}

window.localStorage.setItem('car', JSON.stringify(Car));

Failure to stringify the object will result in an error.

getItem()

This function is used to access or retrieve the data in the local storage. The method takes in a key as a parameter. It then extracts the required value from the localSstorage.

For example, to retrieve the above Car object, we will use the following statement:

window.localStorage.getItem('car');

The above statement will return something like this:

"{brand:"Suzuki",color:"white",price:"10000"}"

You should convert it to an object using JSON.parse() to use it in your code.

JSON.parse(window.localStorage.getItem('car'));

removeItem()

This method is used to delete an item from local storage. The removeItem() method requires a key as a parameter.

window.localStorage.removeItem('brand');

clear()

This method is used to clear all values stored in local storage. It does not require any parameters.

window.localStorage.clear()

Example ::

   
   <!DOCTYPE html>
    <html>
    <body>

        <h1>The Storage setItem() Method</h1>

        <p>This example demonstrates how to use the setItem() method to set the value of a specified local storage item.</p>

            <button onclick="createItem()">Set local storage item</button>

        <h2>Get the value</h2>

        <p>Click the button to get the item value:</p>

            <button onclick="readValue()">Get the item value</button>

        <p id="demo"></p>

        <script>

            function createItem() {
            localStorage.setItem("mytime", Date.now());
            }

            function readValue() {
            var x = localStorage.getItem("mytime");
            document.getElementById("demo").innerHTML = x;
            }

        </script>
    </body>
    </html>