What is the Use of the Window localStorage Property in JavaScript
This article explains the use of the window “localStorage” property in JavaScript.
What is the Use of the Window “localStorage” Property in JavaScript?
The window “localStorage” is a read-only property that refers to the local storage object to store and access the data from its origin. It is used to access any specified storage object values with the help of its name.
Syntax (Save Data to Local Storage)
According to the above syntax, the “localStorage” property uses the “setItem()” method to set a storage object item with two parameters:
- key: It represents the key of the item.
- value: It specifies the value of the specified item.
Syntax (Retrieve Data From Local Storage)
The above syntax uses the “getItem()” method to retrieve the specified storage object item using its name i.e., “key”.
Example: Applying the Window “localStorage” Property to Set and Return the Specific Storage Item
This example applies the practical implementation of the window “localStorage” property to set and retrieve the specific storage item.
HTML Code
First, go through the given HTML code:
In the above code snippet:
- Specify a subheading using the “<h2>” tag.
- Next, add a button with the help of the “<button>” tag comprising an “onclick” event to execute the function “myFunc()” on the button click.
- Lastly, create an empty paragraph via the “<p>” tag that can easily be accessed through its assigned id “demo”.
JavaScript Code
Next, proceed with the below-stated code:
function myFunc() {
localStorage.setItem("Website", "Linuxhint");
document.getElementById("demo").innerHTML = localStorage.getItem("Website");
}
</script>
In the above code block:
- The function named “myFunc()” is defined.
- In its definition, the “localStorage” property is associated with the “setItem()” method to set the specified storage item.
- After that the “getElementById()” method is applied to access the empty paragraph using its id “demo” to append it with the local storage item “value” that is retrieved through the “getItem()” method via its corresponding “key”.
Output
As seen, the output displays the local storage item value upon the button click.
Conclusion
JavaScript window “localStorage” property saves and returns the “key/value” as a localStorage object in the browser with no expiry date. It remains saved in the browser until the user itself does not remove it. It is beneficial to store the data that will be used in the future. This article illustrated the working of the window “localStorage” property in JavaScript.
Source: linuxhint.com