A simple, persistent client-side solution for data caching and offline web functionality.
Data stored remains on the user's browser even after the window is closed or the browser is restarted. This is key for creating seamless offline experiences.
Storage is unique to the origin (protocol + domain + port). Data can only be accessed by pages from the exact same origin, ensuring security and isolation.
Offers a generous amount of storage, typically 5MB to 10MB per origin, making it suitable for caching application state, user preferences, or small datasets.
Interaction is simple and synchronous, using a key-value pair structure where both keys and values must be strings.
.setItem()
Saves data. Key and value must be strings. Use JSON.stringify() for objects/arrays.
.getItem()
Retrieves data using a key. Returns the value string or null if the key doesn't exist.
.removeItem()
Deletes a specific item based on its key. Important for data hygiene and managing storage limits.
.clear()
Completely wipes all key-value pairs stored for the current origin. Use with caution!
// Save todos
const todos = [{id: 1, task: "Buy milk"}];
localStorage.setItem('my_todos', JSON.stringify(todos));
// Load todos (when offline)
const storedTodos = localStorage.getItem('my_todos');
const loadedTodos = storedTodos ? JSON.parse(storedTodos) : [];
console.log(loadedTodos); // Output: [{id: 1, task: "Buy milk"}]