Map in JavaScript (Live Playground)
In JavaScript, the Map
data structure allows you to store key-value pairs, where keys and values can be of any type. A Map
object can be used to store and manipulate collections of key-value pairs efficiently. In this tutorial, we will explore the Map
data structure and its methods.
Creating a Map
To create a Map
, use the Map
constructor. You can create an empty map or initialize it with an iterable object, such as an array of key-value pairs:
const emptyMap = new Map();
const keyValuePairs = [
['one', 1],
['two', 2],
['three', 3],
];
const numbersMap = new Map(keyValuePairs);
numbersMap.forEach((value, key) => console.log(key, value));
Adding Elements
To add elements to a map, use the set
method:
const fruits = new Map();
fruits.set('apple', 5);
fruits.set('banana', 3);
fruits.set('orange', 2);
Accessing Elements
To access a value by its key, use the get
method:
const appleQuantity = fruits.get('apple'); // Returns the value associated with the 'apple' key, otherwise undefined.
Removing Elements
To remove a specific key-value pair from a map, use the delete
method:
fruits.delete('banana'); // Returns true if the key is found and removed, otherwise false.
To remove all elements from a map, use the clear
method:
fruits.clear();
Checking for Elements
To check if a map contains a specific key, use the has
method:
fruits.has('apple'); // Returns true if the key is in the map, otherwise false.
Map Size
To get the number of key-value pairs in a map, use the size
property:
fruits.size; // Returns the number of key-value pairs in the map.
Iterating Over a Map
You can use the forEach
method or a for...of
loop with the entries
, keys
, or values
methods to iterate over a map:
fruits.forEach((value, key) => console.log(key, value));
for (const [key, value] of fruits.entries()) {
console.log(key, value);
}
for (const key of fruits.keys()) {
console.log(key);
}
for (const value of fruits.values()) {
console.log(value);
}
Conclusion
In this tutorial, we've covered the Map
data structure in JavaScript, which allows you to store key-value pairs efficiently. We've explored how to create a map, add and access elements, remove elements, check for elements, determine map size, and iterate over a map. Maps can be particularly useful when you need to store and manipulate collections of key-value pairs.