DEV Community

Rakshambika
Rakshambika

Posted on

Local Storage in JavaScript

What is Local Storage?

  • Local Storage is a web storage feature provided by browsers that allows websites to store data directly in the user's browser. The stored data remains available even after the browser is closed and reopened.

  • It is commonly used to save user preferences, theme settings, shopping cart data, form inputs, and tasks in applications such as To-Do Lists.


Why Do We Need Local Storage?

Normally, JavaScript variables lose their values when a page is refreshed or the browser is closed.

Local Storage helps us preserve data so that it remains available even after refreshing or reopening the browser.


Features of Local Storage

  • Stores data as key-value pairs.
  • Data persists even after the browser is closed.
  • Data is stored in the user's browser.
  • No expiration time.
  • Easy to use with JavaScript.
  • Supported by all modern browsers.

Local Storage Methods

1. setItem()

Used to store data.

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

Enter fullscreen mode Exit fullscreen mode

Here:

"name" is the key.
"Raksha" is the value.

2. getItem()

Used to retrieve stored data.

const name = localStorage.getItem("name");
console.log(name);
Enter fullscreen mode Exit fullscreen mode

Output:

Raksha
Enter fullscreen mode Exit fullscreen mode

3. removeItem()

Used to remove a specific item.

localStorage.removeItem("name");
Enter fullscreen mode Exit fullscreen mode

The key "name" and its value will be deleted.

4. clear()

Used to remove all data from Local Storage.

localStorage.clear();
Enter fullscreen mode Exit fullscreen mode

This deletes every item stored by the website.


Limitations of Local Storage

  • Stores only strings.
  • Limited storage capacity (usually around 5–10 MB).
  • Not suitable for sensitive information such as passwords.
  • Data is accessible through browser developer tools.

Top comments (0)