JavaScript Map clear()
Syntax & Examples
Map.clear() method
The clear() method of the Map object in JavaScript removes all key-value pairs from the Map object, effectively emptying it.
Syntax of Map.clear()
The syntax of Map.clear() method is:
clear()
This clear() method of Map removes all key-value pairs from the Map object.
Return Type
Map.clear() returns value of type undefined
.
✐ Examples
1 Using clear() to empty a Map
In JavaScript, we can use the clear()
method to remove all key-value pairs from a Map object.
For example,
- Create a new Map object
map
with initial key-value pairs. - Use the
clear()
method to remove all key-value pairs from themap
. - Log the updated
map
to the console usingconsole.log()
.
JavaScript Program
const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
map.clear();
console.log(map);
Output
Map {}
2 Using clear() on an already empty Map
In JavaScript, using the clear()
method on an already empty Map object will not cause any errors.
For example,
- Create a new, empty Map object
map
. - Use the
clear()
method to clear themap
. - Log the updated
map
to the console usingconsole.log()
.
JavaScript Program
const map = new Map();
map.clear();
console.log(map);
Output
Map {}
3 Using clear() after adding and removing elements from a Map
In JavaScript, we can use the clear()
method after adding and removing elements from a Map object to empty it completely.
For example,
- Create a new Map object
map
with initial key-value pairs 'a' => 1 and 'b' => 2. - Use the
set()
method to add the key 'c' with the value 3 to themap
. - Use the
delete()
method to remove the key 'a' from themap
. - Use the
clear()
method to remove all remaining key-value pairs from themap
. - Log the updated
map
to the console usingconsole.log()
.
JavaScript Program
const map = new Map([['a', 1], ['b', 2]]);
map.set('c', 3);
map.delete('a');
map.clear();
console.log(map);
Output
Map {}
Summary
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.