localStorage is a browser storage area where we can store data as key-value pairs in the localStorage.
localStorage is separate for each origin (for example, Google and Facebook have separate localStorage objects, so we cannot access the localStorage object of Facebook from Google).
The data stored in localStorage is available to all tabs and windows of the same
The data will not be removed when the browser restarts or the computer powers off.
The following methods are available in the localStorage object:
localStorage.setItem('name', "Ranjith");
localStorage.setItem('age', 25);
localStorage.setItem('height', 170);
localStorage.setItem('weight', 70);
// length
localStorage.length; // 4
// get
localStorage.getItem('age'); // "25"
// remove
localStorage.removeItem('weight');
//length
localStorage.length; // 4
// if the key not present then, null will be returned
localStorage.getItem('weight'); //null
// key
localStorage.key(0); //name
// clear
localStorage.clear();
//length
localStorage.length; // 0
Both the key and value will be stored as String. When we try to save an object, it will be stored as “[object object]”:
localStorage.setItem("obj", {});
localStorage.getItem("obj"); // [object Object]
To store an object in localStorage, we can convert the object to JSONString and store it. Upon accessing the data, we can parse the string to a JSON object:
let user ={
name : "JavaScript Jeep",
age : 23
};
let userStr = JSON.stringify(user);
localStorage.setItem("user", userStr);
let parsedUser = JSON.parse(localStorage.getItem("user"));
parsedUser; // {name: "JavaScript Jeep", age: 23}
We can get and set key-value the same way we do in objects:
// set
localStorage.name = "Raju";
// get
localStorage.name; // "Raju"
// remove
delete localStorage.name;
RELATED TAGS
CONTRIBUTOR
View all Courses