Clearing All Entries
You'll learn how to remove every key-value pair from a Map in one simple operation.
What Does clear() Do?
When you need to empty a Map completely—removing all its entries at once—you use the clear() method. Instead of deleting keys one by one, clear() wipes the slate clean in a single call.
Think of it like clearing a whiteboard: rather than erasing each word individually, you use the eraser to swipe across the entire board at once.
How to Use clear()
The syntax is straightforward—just call clear() on your Map:
const userRoles = new Map();
userRoles.set('alice', 'admin');
userRoles.set('bob', 'editor');
userRoles.set('charlie', 'viewer');
console.log(userRoles.size); // 3
userRoles.clear();
console.log(userRoles.size); // 0
console.log(userRoles.has('alice')); // false
After calling clear(), the Map is completely empty. All keys and values are gone, and size returns 0.
When to Use clear()
Use clear() when you need to reset a Map to its initial empty state:
const cache = new Map();
cache.set('page1', 'data...');
cache.set('page2', 'data...');
// Reset the cache completely
cache.clear();
// Now you can add fresh entries
cache.set('newPage', 'fresh data');
It's more efficient and readable than manually deleting each key, especially when you don't know how many entries exist.
Key Takeaway: The clear() method removes all entries from a Map instantly, resetting it to an empty state—perfect for when you need a fresh start.