- The keys and values in the map collection may be of any type and if a value is added to the map collection using a key which already exists in the collection, then the new value replaces the old value.
- The iteration of elements in a map object is done in the insertion order and a “for…” loop returns an array of all [key, value] pairs for each iteration.
- The keys used in maps can be any type of values such as functions, objects etc whereas the keys in objects are limited to symbols and strings.
- The size of a map can be known easily by using the size property but while dealing with objects, the size has to be determined manually.
- A Map should be preferred in cases where the requirement involves frequent addition and removal of [key, value] pairs because a map is an iterable data type and can be directly iterated whereas iterating an object requires obtaining its keys in a specific manner.
No parameters are required in the Map.clear() method.
Map.clear() method has an undefined return type.
Examples of the above function are provided below.
Input : var myMap = new Map(); myMap.set(0, 'geeksforgeeks'); console.log(myMap.size); myMap.clear(); console.log(myMap.size); Output: 1 0
Explanation: 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.
Input : var myMap = new Map(); myMap.set(0, 'geeksforgeeks'); myMap.set(1, 'is an online portal'); myMap.set(2, 'for geeks'); console.log(myMap.size); myMap.clear(); console.log(myMap.size); Output : 3 0
Explanation: 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.
Codes for the above function are provided below.
- Map.clear() Method is used to remove all the [key, value] pairs of a map.
- If the variable is not of the Map type then the Map.entries() operation throws a TypeError.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.