The delete()
method removes a specified key-value pair from a Map. It returns true
if an element in the Map existed and has been removed, or false
if the element did not exist.
Example 1: Removing a User from a List
// A Map of active users.
const activeUsers = new Map([
['user1', 'Alice'],
['user2', 'Bob']
]);
// Remove 'user2' from the map.
const wasDeleted = activeUsers.delete('user2');
console.log(wasDeleted); // Outputs: true
console.log(activeUsers.has('user2')); // Outputs: false
Explanation
The delete()
method is called with the key 'user2'. The entry is successfully removed, delete()
returns true
, and a subsequent has()
check confirms the key is gone.
Example 2: Attempting to Delete a Non-Existent Entry
// A Map of task statuses.
const taskStatus = new Map([['taskA', 'in-progress']]);
// Try to delete a task that is not in the map.
const result = taskStatus.delete('taskB');
console.log(result); // Outputs: false
Explanation
In this example, delete()
is called with 'taskB', a key that is not in the taskStatus
Map. The method does nothing to the Map and returns false
.
Example 3: Deleting an Entry to Invalidate a Cache
// A simple cache implementation using a Map.
const dataCache = new Map([['/data/1', { 'id': 1, 'content': '...' }]]);
// The data for ID 1 has been updated, so we invalidate the cache entry.
dataCache.delete('/data/1');
console.log(dataCache.has('/data/1')); // Outputs: false
Explanation
Here, delete()
is used to remove a specific entry from a cache. This is a common pattern for cache invalidation when the underlying data has changed.
Example 4: Removing an Entry by Object Reference
// A Map where keys are objects.
const componentState = new Map();
const buttonComponent = { id: 123 };
componentState.set(buttonComponent, { clicked: false });
// To delete the entry, the same object reference must be used.
componentState.delete(buttonComponent);
console.log(componentState.size); // Outputs: 0
Explanation
This demonstrates that to delete an entry with an object key, you must provide a reference to the exact same object that was used to set the entry.
Example 5: Conditional Deletion
// A Map tracking item quantities in a cart.
const shoppingCart = new Map([['apples', 2]]);
const itemToRemove = 'apples';
// Check if the item exists before trying to delete it.
if (shoppingCart.has(itemToRemove)) {
shoppingCart.delete(itemToRemove);
console.log(`${itemToRemove} removed from cart.`);
}
Explanation
This code combines has()
and delete()
for safe removal. It first confirms an item is in the cart before attempting to delete it, preventing unnecessary operations.
Example 6: Using the Return Value of delete()
// A Map of feature toggles.
const featureToggles = new Map([['betaFeature', true]]);
// Delete the feature and log whether it was successful.
if (featureToggles.delete('betaFeature')) {
console.log('Beta feature toggle was successfully removed.');
} else {
console.log('Beta feature toggle was not found.');
}
Explanation
This example explicitly uses the boolean return value of delete()
to provide feedback to the user or system about the outcome of the deletion operation.
Example 7: Deleting the NaN
Key
// A Map containing a NaN key.
const edgeCases = new Map();
edgeCases.set(NaN, 'An interesting case');
// All NaN keys are treated as the same, so this works.
const didDeleteNaN = edgeCases.delete(NaN);
console.log(didDeleteNaN); // Outputs: true
console.log(edgeCases.has(NaN)); // Outputs: false
Explanation
Since Maps treat all NaN
keys as equivalent, you can successfully remove an entry with a NaN
key by passing NaN
to the delete()
method.