clear()


The clear() method removes all key-value pairs from a Map, leaving it empty. This method is a quick way to reset a Map without creating a new one.

Example 1: Resetting a Shopping Cart

// A shopping cart Map with items.
const shoppingCart = new Map([
  ['apples', 2],
  ['oranges', 1]
]);

// The user decides to empty their cart.
shoppingCart.clear();

console.log(shoppingCart.size); // Outputs: 0

Explanation

The clear() method is called on the shoppingCart Map, which removes all its entries. The size of the Map becomes 0 afterward.


Example 2: Clearing a Game State

// A Map holding player scores for a game round.
let playerScores = new Map([
  ['player1', 150],
  ['player2', 200]
]);

// The round ends, so we clear the scores for the next round.
playerScores.clear();

console.log(playerScores.size); // Outputs: 0

Explanation

This shows how clear() can be used to reset game state. Instead of reassigning the playerScores variable, we simply empty the existing Map.


Example 3: Invalidating an Entire Cache

// A Map used for caching API results.
let apiCache = new Map([
  ['/users', [{ 'name': 'John' }]],
  ['/products', [{ 'name': 'Laptop' }]]
]);

// A global event (e.g., user logout) requires clearing the entire cache.
apiCache.clear();

console.log(apiCache.size); // Outputs: 0

Explanation

In this scenario, clear() provides an efficient way to invalidate all entries in a cache at once, which is useful during events like user logout or a major data refresh.


Example 4: Re-populating a Map after Clearing

// A Map for daily tasks.
let dailyTasks = new Map([['morning', 'Team meeting']]);

// Clear yesterday's tasks.
dailyTasks.clear();

// Add today's tasks.
dailyTasks.set('morning', 'Code review');
dailyTasks.set('afternoon', 'Project planning');

console.log(dailyTasks.size); // Outputs: 2

Explanation

This example illustrates a common workflow: clearing a Map of old data before populating it with new data, all while using the same Map object.


Example 5: Clearing a Map of Event Listeners

// A Map to manage custom event listeners.
let eventHandlers = new Map();
eventHandlers.set('click', () => console.log('Clicked!'));

// When a component is destroyed, clean up all its listeners.
eventHandlers.clear();

console.log(eventHandlers.size); // Outputs: 0

Explanation

When managing resources like event listeners, clear() is essential for cleanup. It helps prevent memory leaks by removing all references held by the Map.


Example 6: Effect of clear() on an Empty Map

// An already empty Map.
const emptyMap = new Map();

console.log(emptyMap.size); // Outputs: 0

// Clearing an empty map has no effect and does not cause an error.
emptyMap.clear();

console.log(emptyMap.size); // Outputs: 0

Explanation

Calling clear() on a Map that is already empty is a safe operation. It does not change the Map or throw an error.


Example 7: Clearing and Preserving the Reference

// A Map referenced by multiple parts of an application.
let sharedState = new Map([['status', 'active']]);
let anotherReference = sharedState;

// Clearing the map affects all references to it.
sharedState.clear();

console.log(sharedState.size);     // Outputs: 0
console.log(anotherReference.size); // Outputs: 0

Explanation

This demonstrates that clear() modifies the Map object in place. Any other variables that reference the same Map will see the change, as they all point to the same object in memory.