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
- Data is stored as
string
key-value pairs. - It is synchronous (blocking operations).
- Data persists even after the browser window is closed.
- Storage size is around 5MB per origin.
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
- Remembering theme preferences (dark/light mode)
- Storing authentication tokens
- Saving form inputs temporarily
- Persisting game progress or scores
Best Practices
- Always use
try...catch
withJSON.parse()
to avoid errors with corrupted or missing data. - Clean up storage when data is no longer needed.
- Do not store sensitive information (e.g., passwords) in local storage.
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.