Local Storage is a built-in feature of web browsers that allows websites to store key-value pairs in a web browser with no expiration date. This means the data persists even after the browser is closed and reopened, making it useful for saving user preferences, session data, and more.
What is Local Storage?
- Capacity: Approximately 5MB per domain.
- Persistence: Data remains until explicitly deleted.
- Scope: Accessible only from the same origin (protocol, host, and port).
- Data Type: Stores data as strings.
- Synchronous: Operations are synchronous and may block the main thread for large amounts of data.
Basic Methods
| Operation | Method | Description |
|---|---|---|
| Create/Update | localStorage.setItem(key, value) |
Stores a key-value pair |
| Read | localStorage.getItem(key) |
Retrieves the value for a key |
| Delete | localStorage.removeItem(key) |
Removes a key-value pair |
| Clear All | localStorage.clear() |
Clears all storage |
| Length | localStorage.length |
Number of stored items |
| Get Key Name | localStorage.key(index) |
Returns key name by index |
How to Use Local Storage
Storing and Retrieving a String
// Store data
localStorage.setItem('username', 'JohnDoe');
// Retrieve data
const username = localStorage.getItem('username');
console.log(username); // Output: JohnDoe
Removing a Specific Item
localStorage.removeItem('username');
Clearing All Items
localStorage.clear();
Handling Non-String Data
Since Local Storage only saves strings, objects and arrays must be serialized using JSON.stringify() when saving and JSON.parse() when retrieving.
// Store an object
const user = { name: 'John', age: 30 };
localStorage.setItem('user', JSON.stringify(user));
// Retrieve and parse the object
const retrievedUser = JSON.parse(localStorage.getItem('user'));
console.log(retrievedUser.name); // Output: John
Advanced Examples
1. Persisting Dark Mode Preference
Save the user’s dark mode preference and apply it automatically on page load.
// Toggle Dark Mode
function toggleDarkMode() {
document.body.classList.toggle('dark-mode');
const isDarkMode = document.body.classList.contains('dark-mode');
localStorage.setItem('darkMode', isDarkMode);
}
// Load Dark Mode on page load
window.addEventListener('DOMContentLoaded', () => {
const darkMode = localStorage.getItem('darkMode');
if (darkMode === 'true') {
document.body.classList.add('dark-mode');
}
});
Tip: You can bind
toggleDarkModeto a button click to let users switch modes.
2. Shopping Cart Persistence
Build a simple shopping cart that persists across sessions.
// Add item to cart
function addToCart(item) {
let cart = JSON.parse(localStorage.getItem('cart')) || [];
cart.push(item);
localStorage.setItem('cart', JSON.stringify(cart));
}
// Get cart items
function getCartItems() {
return JSON.parse(localStorage.getItem('cart')) || [];
}
// Example usage
addToCart({ id: 1, name: 'Laptop', price: 1200 });
addToCart({ id: 2, name: 'Mouse', price: 25 });
console.log(getCartItems());
Tip: Always validate and sanitize data before storing user-generated content
Best Practices
- Use JSON: Always serialize complex data structures.
- Limit Storage Size: Keep data minimal; Local Storage is not meant for large data.
- Handle Errors: Always wrap Local Storage operations in
try-catchblocks to prevent browser quota errors. - Secure Sensitive Data: Never store sensitive information like passwords or tokens.
Conclusion
Local Storage is a powerful tool for front-end developers to persist lightweight data across sessions without server-side involvement. By understanding how to implement and manage it properly, you can greatly improve your application’s performance and user experience.