JavaScript ES6 Map and Set: Complete Guide
JavaScript ES6 introduced two powerful data structures: Map and Set. Both of these structures allow for more efficient data management and manipulation, which can enhance your coding practices. In this complete guide, we will explore the key features, differences, and practical uses of Map and Set.
What is a Map?
A Map is a collection of keyed data items, similar to an object but with some notable differences. Maps can store any type of values (both objects and primitive values) as keys. This flexibility makes Maps particularly useful when you need to associate values with unique keys.
Key Features of Map
- Ordered: Maps maintain the order of the keys based on their insertion sequence.
- Flexible Keys: Any value (including objects) can be used as a key.
- Iterable: Maps can be iterated over using loops such as
forEach
orfor...of
.
Creating and Using Maps
Creating a Map is straightforward:
const myMap = new Map();
You can also initialize a Map with key-value pairs:
const myMap = new Map([
['key1', 'value1'],
['key2', 'value2']
]);
Commonly used methods include:
set(key, value)
: Adds a new key-value pair.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.
What is a Set?
A Set is a collection of unique values. It does not allow duplicate values, making it a great choice when you need to store unique items. Like Maps, Sets can also store objects and other weak references.
Key Features of Set
- Unique Values: Sets automatically enforce uniqueness of the stored values.
- Ordered: Sets maintain the order of elements based on their insertion sequence.
- Iterable: Sets support iteration through loops and generator functions.
Creating and Using Sets
Creating a Set is very similar to creating a Map:
const mySet = new Set();
You can also initialize a Set with an array of unique values:
const mySet = new Set([1, 2, 3]);
Key methods for Sets include:
add(value)
: Adds a new value to the Set.has(value)
: Checks if a value exists in the Set.delete(value)
: Removes a value from the Set.clear()
: Clears all values from the Set.
Differences Between Map and Set
While both Map and Set are part of the ES6 specification and allow for efficient data handling, they serve different purposes:
- Values vs. Key-Value Pairs: Maps store key-value pairs, while Sets store unique values.
- Key Usage: Map allows any data type as a key, whereas a Set does not have this structure.
When to Use Map vs Set
Choose Map when:
- You need to associate values with unique keys.
- You require ordered key-value pairs for iteration.
Choose Set when:
- You need to store a collection of unique values.
- You want to quickly check for the existence of a value.
Conclusion