- 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 iterative data type and can be directly iterated whereas iterating an object requires obtaining its keys in a specific manner.
The Map.delete() method takes the key which needs to be removed from the map, thus removes the element associated with that key and returns true. If the key is not present then it returns false.
- Map.delete() is used to delete an element associated with the key among all the elements present in the map.
- key: The element associated with this key is to be removed from the map
- The Map.delete() method returns true, if the key is present whose associated element is to removed which is passed as an argument, otherwise returns false.
Input : my_map.set(1, 'first'); my_map.set(2, 'second'); my_map.set(3,'third'); my_map.set(4,'fourth'); document.write(my_map.delete(3)); Output : true
Explanation: The key ‘3’ is present in the map hence element associated with it is removed and return true
Input : my_map.set(1, 'first'); my_map.set(2, 'second'); my_map.set(3,'third'); my_map.set(4,'fourth'); document.write(my_map.delete(5)); Output : false
Explanation: The key ‘5’ is not present in the map hence it returns false.
true key-value pair of the map after deletion- 1: first 2: second 4: fourth
false key-value pair of the map after deletion- 1: first 2: second 3: third 4: fourth
Error and Exception:
- If the key passed as an argument to the function is not present in the map then it returns false. Basically, it neither throws any exception nor does it have any error.
Difference in working of Map.clear(),Map.erase() and this function
Map.clear() removes all key-value pairs of the map and reduces the size of the map to zero. Whereas Map.erase() removes the specified mapped value whose key is passed as an argument or iterator or in range to remove pairs.
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.