The clear() method of the Map object in JavaScript removes all key-value pairs from the Map object, effectively emptying it.
The syntax of Map.clear() method is:
clear()
This clear() method of Map removes all key-value pairs from the Map object.
Map.clear() returns value of type undefined
.
In JavaScript, we can use the clear()
method to remove all key-value pairs from a Map object.
For example,
map
with initial key-value pairs.clear()
method to remove all key-value pairs from the map
.map
to the console using console.log()
.const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
map.clear();
console.log(map);
Map {}
In JavaScript, using the clear()
method on an already empty Map object will not cause any errors.
For example,
map
.clear()
method to clear the map
.map
to the console using console.log()
.const map = new Map();
map.clear();
console.log(map);
Map {}
In JavaScript, we can use the clear()
method after adding and removing elements from a Map object to empty it completely.
For example,
map
with initial key-value pairs 'a' => 1 and 'b' => 2.set()
method to add the key 'c' with the value 3 to the map
.delete()
method to remove the key 'a' from the map
.clear()
method to remove all remaining key-value pairs from the map
.map
to the console using console.log()
.const map = new Map([['a', 1], ['b', 2]]);
map.set('c', 3);
map.delete('a');
map.clear();
console.log(map);
Map {}
In this JavaScript tutorial, we learned about clear() method of Map: the syntax and few working examples with output and detailed explanation for each example.