LocalStorage in JavaScript - Complete Guide with Real Examples
Master localStorage in JavaScript with this complete guide. Learn how to persist data in the browser with practical examples from real projects.
LocalStorage in JavaScript - Complete Guide
LocalStorage is one of the most useful browser APIs for storing data on the client side. Let's learn how to use it effectively.
What is LocalStorage?
LocalStorage allows you to store key-value pairs in the browser that persist even after the page is closed.
Key features:
- •Storage limit: ~5-10MB per domain
- •Stores only strings
- •Synchronous API
- •No expiration time
- •Accessible only from same origin
Basic Operations
1. Storing Data
// Store a string
localStorage.setItem('username', 'John');
// Store a number (will be converted to string)
localStorage.setItem('age', 25);
// Store an object (must stringify first)
const user = { name: 'John', age: 25 };
localStorage.setItem('user', JSON.stringify(user));2. Retrieving Data
// Get a string
const username = localStorage.getItem('username');
// Get and parse an object
const userString = localStorage.getItem('user');
const user = JSON.parse(userString);3. Removing Data
// Remove a specific item
localStorage.removeItem('username');
// Clear all localStorage
localStorage.clear();4. Checking if Key Exists
if (localStorage.getItem('username')) {
console.log('Username exists');
}
// Or check all keys
const hasUser = Object.keys(localStorage).includes('username');Real-World Examples
Example 1: Dark Mode Preference
// Save dark mode preference
function toggleDarkMode() {
const isDark = document.body.classList.toggle('dark-mode');
localStorage.setItem('darkMode', isDark);
}
// Load dark mode on page load
window.addEventListener('DOMContentLoaded', () => {
const isDark = localStorage.getItem('darkMode') === 'true';
if (isDark) {
document.body.classList.add('dark-mode');
}
});Example 2: Todo List Persistence
// Save todos array
function saveTodos(todos) {
localStorage.setItem('todos', JSON.stringify(todos));
}
// Load todos on app start
function loadTodos() {
const todosString = localStorage.getItem('todos');
return todosString ? JSON.parse(todosString) : [];
}
// Usage
let todos = loadTodos();Example 3: Form Data Auto-save
// Auto-save form input
const input = document.getElementById('email');
input.addEventListener('input', (e) => {
localStorage.setItem('draft_email', e.target.value);
});
// Restore on page load
window.addEventListener('DOMContentLoaded', () => {
const draft = localStorage.getItem('draft_email');
if (draft) {
input.value = draft;
}
});Best Practices
1. Always Handle Errors
function safeSetItem(key, value) {
try {
localStorage.setItem(key, value);
return true;
} catch (e) {
if (e.name === 'QuotaExceededError') {
console.error('Storage quota exceeded');
}
return false;
}
}2. Use Helper Functions
const storage = {
set(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
return true;
} catch (e) {
return false;
}
},
get(key, defaultValue = null) {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : defaultValue;
} catch (e) {
return defaultValue;
}
},
remove(key) {
localStorage.removeItem(key);
},
clear() {
localStorage.clear();
}
};
// Usage
storage.set('user', { name: 'John' });
const user = storage.get('user');3. Namespace Your Keys
// Bad
localStorage.setItem('todos', '[]');
localStorage.setItem('settings', '{}');
// Good - prefix with app name
localStorage.setItem('myapp_todos', '[]');
localStorage.setItem('myapp_settings', '{}');Common Pitfalls
❌ Not Checking for Browser Support
// Always check first
if (typeof Storage !== 'undefined') {
localStorage.setItem('key', 'value');
} else {
console.log('LocalStorage not supported');
}❌ Storing Sensitive Data
Never store:
- •Passwords
- •Credit card numbers
- •API keys
- •Personal identification
❌ Forgetting to Parse JSON
// Wrong
const todos = localStorage.getItem('todos');
todos.push(newTodo); // Error! todos is a string
// Correct
const todos = JSON.parse(localStorage.getItem('todos'));
todos.push(newTodo);LocalStorage vs SessionStorage vs Cookies
| Feature | LocalStorage | SessionStorage | Cookies |
|---------|-------------|----------------|---------|
| Capacity | ~5-10MB | ~5-10MB | ~4KB |
| Expiration | Never | Tab close | Configurable |
| Sent to server | No | No | Yes |
| Accessible from | JavaScript | JavaScript | JS & Server |
Projects Using LocalStorage
See localStorage in action:
- •BMI Calculator - History storage
- •Advanced Todo App - Full CRUD with localStorage
- •Digital Clock - Settings persistence
Further Reading
Start building projects with localStorage today! 🚀
🚀Build These Projects
Put what you learned into practice with these hands-on projects
BMI Calculator
A responsive BMI Calculator built using Vanilla JavaScript that calculates BMI, shows health categories, and stores previous results using localStorage.
Advanced Todo App
An advanced Todo App featuring categories, priorities, filters, statistics, dark mode, and persistent storage.
Digital Clock
A multi-feature Digital Clock application built with Vanilla JavaScript that includes a real-time clock, stopwatch with lap tracking, and a countdown timer with alerts.
📚Continue Learning
Explore more tutorials and guides
50+ JavaScript Interview Questions & Answers (2026) — Beginner to Advanced
50+ most asked JavaScript interview questions with clear, detailed answers. From beginner basics to advanced concepts like closures, event loop, prototypes, and async patterns — everything you need to crack your next JS interview.
How to Build a Weather App in JavaScript - Complete Fetch API Tutorial
Build a real-time Weather App with JavaScript from scratch. Learn the Fetch API, async/await error handling, Geolocation API, and how to integrate OpenWeatherMap in this complete step-by-step tutorial.
DOM Manipulation JavaScript Hindi: Complete Guide with Real Examples
DOM Manipulation JavaScript ka sabse important concept hai! Is guide mein seekho getElementById, querySelector, createElement, Events - sab kuch Hindi mein real examples ke saath.