Deleting Storage Data: removeItem and clear
You'll learn how to delete individual items from storage or wipe all stored data at once.
Cleaning Up Your Storage
Just as important as storing data is knowing how to remove it. Web Storage gives you two methods for deletion: removeItem() for surgical removal of specific items, and clear() for wiping the slate completely clean.
Think of it like managing photos on your phone: sometimes you delete one bad selfie (removeItem), and sometimes you clear out your entire camera roll to start fresh (clear).
Using removeItem()
removeItem() deletes a single key-value pair from storage. You pass the key name as an argument:
// Remove just the username
localStorage.removeItem('username');
// Try to get it now - returns null
const user = localStorage.getItem('username');
console.log(user); // null
If you call removeItem() with a key that doesn't exist, nothing happens—no error is thrown.
Using clear()
clear() removes everything from that storage object. It takes no arguments and nukes all data:
// Store multiple items
localStorage.setItem('username', 'Alex');
localStorage.setItem('theme', 'dark');
localStorage.setItem('score', '1500');
// Wipe everything
localStorage.clear();
// All gone
console.log(localStorage.getItem('username')); // null
console.log(localStorage.getItem('theme')); // null
When to Use Each
Use removeItem() when a user logs out (remove their session token), changes settings (remove an old preference), or you need targeted cleanup. Use clear() when resetting app state, implementing a "clear all data" feature, or during testing.
Key Takeaway: Use removeItem(key) to delete one item at a time, or clear() to erase all storage data in one go—choose based on whether you need precision or a complete reset.