Open In App

What is the use of the Map.prototype.clear method in JavaScript Maps ?

Last Updated : 01 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, the Map.prototype.clear method is used to remove all key-value pairs from a Map, effectively making the Map empty. It does not take any arguments and does not return any value.

Syntax:

myMap.clear();
  • myMap: The Map from which you want to remove all key-value pairs.

Example: Here, a map object “myMap” has been created with a single [key, value] pair, and the Map.clear() method is used to remove the [key, value] pair from “myMap”. myMap.size() is used to check the number of [key, value] pairs belonging to the map object.

Javascript




// Creating a map object
let myMap = new Map();
 
// Adding [key, value] pair to the map
myMap.set(0, 'geeksforgeeks');
 
// Displaying the number of
// [key, value] pairs the map has
console.log(myMap.size);
 
// Removing the [key, value] pairs of
// the map using Map.clear() method
myMap.clear();
 
// Displaying the number of
// [key, value] pairs the map has
console.log(myMap.size);


Output

1
0

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads