Friday, September 5, 2025
HomeLanguagesJavascriptJavaScript Map clear() Method

JavaScript Map clear() Method

JavaScript Map.clear() method is used for the removal of all the elements from a map and making it empty. It removes all the [key, value] from the map. No arguments are required to be sent as parameters to the Map.clear() method and it returns an undefined return value.

Syntax:

mapObj.clear()

Parameters: No parameters are required in the Map.clear() method.

Return Value: Map.clear() method has an undefined return type.

Examples of the above method are provided below.

Example 1: In this example, 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, 'neveropen');
 
// 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

Example 2: In this example, a map object “myMap” has been created with a three [key, value] pairs and the Map.clear() method is used to remove all the [key, value] pairs 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, 'neveropen');
myMap.set(1, 'is an online portal');
myMap.set(2, 'for neveropen');
 
// 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 :

3
0

Applications:

  • Map.clear() Method is used to remove all the [key, value] pairs of a map.

Exceptions :

  • If the variable is not of the Map type then the Map.entries() operation throws a TypeError.

We have a complete list of Javascript Map methods, to check them please go through the Javascript Map Complete Reference article.

Supported Browsers: 

  • Chrome 38 and above
  • Edge 12 and above
  • Firefox 19 and above
  • Internet Explorer 11 and above
  • Opera 25 and above
  • Safari 8 and above
RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6636 POSTS0 COMMENTS
Nicole Veronica
11802 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11865 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7027 POSTS0 COMMENTS
Thapelo Manthata
6703 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS