The delete() method can be utilized to remove an element from a Map object. This method takes the key name of the element as a parameter. It returns true if the element was present in the Map object and successfully removed, or false if the element does not exist.

const map = new Map([
  ['name', 'Alex Hales'],
  ['age', 27],
  ['country', 'United States']
])

console.log(map)
// Map(3) {
//   'name' => 'Alex Hales',
//   'age' => 27,
//   'country' => 'United States'
// }

console.log(map.delete('name')) // true
console.log(map.delete('name')) // false (already removed)
console.log(map.delete('job')) // false (not found)

To delete all elements in a Map object, the clear() method can be used:

const map = new Map([
  ['name', 'Alex Hales'],
  ['age', 27],
  ['country', 'United States']
])

map.clear()

console.log(map.size) // 0
console.log(map) // Map(0) {}

To gain a deeper understanding of the Map object and how to create collections of key-value pairs in JavaScript, refer to this article.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.