In this article, we will learn all the methods related to the map.
But first, what is a map?
The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value. (MDN Definition)
How to creata map
Well, now we know the general definition of a map, but how do we create a map?
its very easy
const map = new Map([]);
console.log(map);
// Map(0) {}
Now we have created a map, but there are no elements in it, so how do we add an element?
Add elements to a Map
We can use set
method to add elements to map.
Example
// Map
const map = new Map();
// Set elements
map.set('name', 'John');
map.set('age', 30);
// Result:
console.log(map);
Output
Map(2) { 'name' => 'John', 'age' => 30 }
Can we update this element? Yes we can
Update an element in a map
We can also easily update the element in the map using set
method.
// Map
const map = new Map([
['name', 'John'],
['age', 30]
]);
// Update an element if exists
map.set('name', 'Doe');
// Add new element (because not exists)
map.set('country', 'USA');
Output
Map(3) { 'name' => 'Doe', 'age' => 30, 'country' => 'USA' }
Well, if we want to delete an element from the map, can we do that? Yes we can
Delete an element from a map
We can delete an element from a map using delete
method.
Example
// Map
const map = new Map([
['name', 'John'],
['age', 30],
['country', 'USA']
]);
// before deletion
console.log(map);
// delete an elemetn
map.delete('country');
// after deletion
console.log(map);
Output
Map(3) { 'name' => 'John', 'age' => 30, 'country' => 'USA' }
Map(2) { 'name' => 'John', 'age' => 30 }
And if we want to delete all elements, will we delete every item? The answer is no
Delete all elements from map
We can delete all elements from map using clear
method
Example
// Map
const map = new Map([
['name', 'John'],
['age', 30],
['country', 'USA']
]);
// Clear
map.clear();
// Result:
console.log(map);
Output
Map(0) {}
Get an element from a Map
You can use the get()
method to get elements from a Map
// Map
const map = new Map([
['name', 'John'],
['age', 30],
['country', 'USA']
]);
// Get an element
console.log(map.get('name'));
Output
John
Get the number of elements in a map
We can get the number of elements using size
property.
Example
// Map
const map = new Map([
['name', 'John'],
['age', 30],
['country', 'USA']
]);
// Result:
console.log(map.size);
Output
3
Check if an element exists in a Map
We can check if an elements exists using has
method.
Example
const map = new Map([
['name', 'John'],
['age', 30],
['country', 'USA']
]);
console.log(map.has('name'));
console.log(map.has('isMarried'));
Output
true
false
Thank you for reading
Thank you for reading my blog. 🚀