JavaScript
Local Storage



What is Local Storage?

Local Storage is a built-in browser feature that allows developers to store key-value pairs in a web browser, accessible even after the browser is closed and reopened. It is part of the Web Storage API and is useful for persisting user data like theme preferences, tokens, or form inputs.

Key Characteristics of Local Storage

Basic Operations with Local Storage

1. Storing Data using localStorage.setItem()

This method allows you to store a key-value pair in local storage.


localStorage.setItem('username', 'john_doe');
    

Output:

The key "username" with value "john_doe" is saved in the browser's local storage.

Question: What happens if we store the same key again?

Answer: It will overwrite the existing value with the new one.

2. Retrieving Data using localStorage.getItem()

Use this method to retrieve the value of a stored key.


const user = localStorage.getItem('username');
console.log(user);
    

Output:

john_doe

3. Removing Data using localStorage.removeItem()

Use this to delete a specific key-value pair.


localStorage.removeItem('username');
    

Output:

The key "username" is removed from local storage.

4. Clearing All Data using localStorage.clear()

This method removes all key-value pairs from local storage.


localStorage.clear();
    

Output:

All keys and values in local storage are deleted.

Storing Complex Data (Objects & Arrays)

Since local storage only stores strings, you need to use JSON.stringify() to store objects or arrays, and JSON.parse() to retrieve them.

Example: Store and Retrieve an Object


const userDetails = {
  name: "Alice",
  age: 25,
  loggedIn: true
};

// Store the object
localStorage.setItem("userDetails", JSON.stringify(userDetails));

// Retrieve the object
const storedData = JSON.parse(localStorage.getItem("userDetails"));
console.log(storedData);
    

Output:

{ name: "Alice", age: 25, loggedIn: true }

Question: What happens if you skip JSON.stringify()?

Answer: The object will be stored as [object Object], which is not useful.

Use Cases of Local Storage

Best Practices

Common Mistake to Avoid

Trying to store a number, boolean, or object directly without converting it to a string:


// Mistake
localStorage.setItem("isAdmin", true);

// Correct
localStorage.setItem("isAdmin", JSON.stringify(true));
    

Summary

Local Storage in JavaScript is a simple yet powerful tool for storing data persistently in the browser. It is ideal for lightweight storage needs that don’t require server communication. Always convert non-string data using JSON.stringify() and handle parsing with JSON.parse() carefully.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M