LocalStorage.setItem JavaScript Example

LocalStorage.setItem() Method: Add key and value to LocalStorage.

Syntax

window.localStorage
The syntax for SAVING data to localStorage:
localStorage.setItem("key", "value");

localStorage.setItem() Method Example

This method just as the name implies allows you to store values in the localStorage object.
It takes two parameters, a key, and a value. The key can be referenced later to fetch the value attached to it.
localStorage.setItem("firstName", "Ramesh");
Where "firstName" is the key and "Ramesh" is the value. Also, note that localStorage can only store strings.
To store arrays or objects you would have to convert them to strings.
To do this we use the JSON.stringify() method before passing to setItem() .
var user = {
 firstName : "Ramesh",
 lastName : "Fadatare"
}
localStorage.setItem("id", JSON.stringify(user));

Reference


Comments