When I started learning JavaScript, I learned how to store data in variables. But I had one question: What happens to the data when we refresh the webpage?
Normally, data stored only in variables is lost when the page reloads. That's where localStorage becomes useful!
What is LocalStorage?
localStorage is a browser feature that allows us to store data in the user's browser.
The best part? The data stays saved even after refreshing or closing the browser, until it is removed by the user or the application.
- Store Data Using setItem()
We can save data using localStorage.setItem().
localStorage.setItem("name", "Narasimma");
Here:
"name" is the key.
"Narasimma" is the value.
- Get Data Using getItem()
We can retrieve the saved data using getItem().
let name = localStorage.getItem("name");
console.log(name);
Output:
Narasimma
- Remove Data Using removeItem()
Want to remove a particular item?
localStorage.removeItem("name");
This removes the data stored with the key "name".
- Clear All Data Using clear()
localStorage.clear();
This removes all entries from the website's local storage. Use it carefully!
- Store Objects and Arrays
One important thing to remember is that localStorage stores values as strings.
To store an object or array, we can use JSON.stringify().
let student = {
name: "Arun",
age: 21
};
localStorage.setItem("student", JSON.stringify(student));
To retrieve the object, use JSON.parse().
let data = JSON.parse(localStorage.getItem("student"));
console.log(data.name);
Output:
Arun
Where Can We Use LocalStorage?
Saving a user's theme preference
Remembering form data
Storing shopping cart information
Saving simple application settings
Building small projects without a backend
Top comments (0)