JavaScript Map
In JavaScript, a Map is a powerful data structure that stores key-value pairs. Unlike objects, which can only have strings or symbols as keys, Maps can have keys of any type, including objects, functions, and primitive values. The Map object also provides useful methods for iterating over its contents, checking its size, and getting, setting, and deleting items.
A Map is a collection of key-value pairs where both the key and the value can be any data type, unlike objects, which only allow strings and symbols as keys.
You can create a Map using the new Map()
constructor:
const myMap = new Map();
This creates an empty map. You can also initialize a map with key-value pairs when creating it:
const myMap = new Map([
['name', 'John'],
['age', 30],
['city', 'New York']
]);
Here, ['name', 'John']
, ['age', 30]
, and ['city', 'New York']
are key-value pairs, where the first element is the key and the second is the value.
size
property of a Map tells you the number of key-value pairs it contains.To add a new key-value pair to a Map, you can use the set()
method.
const myMap = new Map();
myMap.set('name', 'Alice');
myMap.set('age', 25);
myMap.set('city', 'Los Angeles');
In this example, we use the set()
method to add three key-value pairs to the Map.
To retrieve the value associated with a key, you can use the get()
method.
const name = myMap.get('name');
console.log(name); // Output: Alice
To check if a key exists in a Map, use the has()
method.
const hasCity = myMap.has('city');
console.log(hasCity); // Output: true
To remove a key-value pair from a Map, use the delete()
method.
myMap.delete('age');
console.log(myMap.has('age')); // Output: false
To remove all the key-value pairs from a Map, use the clear()
method.
myMap.clear();
console.log(myMap.size); // Output: 0
Maps provide several ways to iterate over the key-value pairs:
forEach()
The forEach()
method allows you to iterate over the Map and execute a function on each key-value pair.
myMap.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
for...of
LoopYou can also use a for...of
loop to iterate over the entries of the Map. The entries()
method returns an iterator for the key-value pairs.
for (let [key, value] of myMap) {
console.log(`${key}: ${value}`);
}
This will output each key-value pair in the Map.
If you want to iterate over only the keys or values of a Map, you can use the keys()
and values()
methods, respectively.
// Iterate over the keys
for (let key of myMap.keys()) {
console.log(key);
}
// Iterate over the values
for (let value of myMap.values()) {
console.log(value);
}
Maps come with several useful methods that help with different operations:
set(key, value)
: Adds a new key-value pair or updates an existing one.get(key)
: Retrieves the value associated with the key.has(key)
: Checks if a key exists in the Map.delete(key)
: Removes a key-value pair.clear()
: Clears all key-value pairs.size
: Returns the number of key-value pairs.keys()
: Returns an iterator for the keys in the Map.values()
: Returns an iterator for the values in the Map.entries()
: Returns an iterator for the key-value pairs.forEach(callback)
: Executes a callback for each key-value pair.While both Maps and Objects store key-value pairs, there are key differences between the two:
Feature | Map | Object |
---|---|---|
Key Type | Any type (primitive, object, function) | Only strings and symbols as keys |
Iteration Order | Maintains insertion order | Does not guarantee insertion order |
Size Property | Has a size property |
Does not have a size property |
Performance (for large data) | Optimized for frequent additions/removals | Slower for large sets of data |
Methods | .set() , .get() , .has() , .delete() |
Access via bracket or dot notation |
The Map object is often used in scenarios where you need to:
Here are some real-world use cases for Map: