Introduction
Web Storage API is one of the popular JavaScript(JS) APIs. It is used for storing and retrieving data in the browser. It gives a mechanism by which browsers can store key/value pairs much better than using cookies. It is also very easy to use.
The localStorage object
The localStorage object, part of the web storage API, gives us access to the local storage for a particular Web Site. It allows you to store, read, add, modify, and delete data items for that domain. The data does not have an expiry date and will not get deleted when the browser is closed.
This functionality is compatible even when the websites are browsed in 'incognito' or 'private' mode. However, the data is kept only until you quit the browser.
The setItem() Method
The localStorage.setItem() method is used to store a data item in storage. If it already exists, then an update over the value of the existing key takes place.
Syntax:
// Parameters are the keys name and its value
localStorage.setItem(keysName, keysValue);
The getItem() Method
When the localStorage.getItem() method is passed a key name, it will return its corresponding value. If the value of a non-existing key is requested, then it returns null.
Syntax:
// Value of key stored to variable storedValue
var storedValue = localStorage.getItem(keysName);
Let's understand the methods of the localStorage object with the help of an example.
Code:
<!DOCTYPE html>
<html>
<body>
<p id="test"></p>
<script>
localStorage.setItem("Name","Ninja");
document.getElementById("test").innerHTML = localStorage.getItem("Name");
</script>
</body>
</html>
Output
Try and compile by yourself with the help of online javascript compiler for better understanding.