Course contentsShow
← JavaScript
Lesson 1036 of 2,72324. Maps and SetsFree lesson

Deleting Entries

Removing key-value pairs with delete() and its return value.

Deleting Entries

You'll learn how to remove key-value pairs from a Map and understand what the delete operation tells you.

How Map Deletion Works

Once you've added entries to a Map, you'll often need to remove them. The delete() method lets you remove a specific key-value pair by targeting its key. Unlike working with objects where you'd use the delete operator, Maps have a dedicated method that's both cleaner and more informative.

Think of it like removing a contact from your phone's address book. You search by name (the key), and if that contact exists, you delete it. Your phone then confirms whether the deletion actually happened.

The delete() Method

Call delete() on your Map with the key you want to remove:

const user = new Map();
user.set('name', 'Alice');
user.set('age', 28);

user.delete('age');  // Removes the 'age' entry
console.log(user.has('age'));  // false

The Return Value Matters

Here's what makes delete() particularly useful: it returns true if the key existed and was deleted, or false if the key wasn't found:

const colors = new Map([['sky', 'blue'], ['grass', 'green']]);

console.log(colors.delete('sky'));    // true (existed, now deleted)
console.log(colors.delete('ocean'));  // false (never existed)
console.log(colors.delete('sky'));    // false (already deleted)

This return value lets you know whether your deletion actually did something, which is helpful for error handling or conditional logic.

Key Takeaway: Use map.delete(key) to remove entries from a Map; it returns true if the key was found and deleted, false otherwise.