DEV Community

Narasimma Radhakrishnan
Narasimma Radhakrishnan

Posted on

LocalStorage in JavaScript for Beginners 💾

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.

  1. Store Data Using setItem()

We can save data using localStorage.setItem().

localStorage.setItem("name", "Narasimma");

Here:

"name" is the key.

"Narasimma" is the value.

  1. Get Data Using getItem()

We can retrieve the saved data using getItem().

let name = localStorage.getItem("name");

console.log(name);

Output:

Narasimma

  1. Remove Data Using removeItem()

Want to remove a particular item?

localStorage.removeItem("name");

This removes the data stored with the key "name".

  1. Clear All Data Using clear()

localStorage.clear();

This removes all entries from the website's local storage. Use it carefully!

  1. 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));
Enter fullscreen mode Exit fullscreen mode

To retrieve the object, use JSON.parse().

let data = JSON.parse(localStorage.getItem("student"));

console.log(data.name);
Enter fullscreen mode Exit fullscreen mode

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)