20 Feb 2024
Intermediate
In JavaScript, both Map and Set are data structures that allow you to store collections of values, but they have different purposes and characteristics.
Map:
-
Key-Value Pairs:
- A Map is a collection of key-value pairs, where each key and value can be of any data type.
- Keys can be objects, functions, or any primitive values.
-
Ordering:
- The order of elements in a Map is based on the order in which they were inserted.
-
Duplicate Keys:
- Each key in a Map must be unique. If you try to add a key that already exists, it will overwrite the existing key-value pair.
-
Methods:
- Maps provide methods for adding, removing, and checking the presence of key-value pairs.
- Examples of Map methods include
set(),get(),has(), anddelete().
// Example of a Map
let myMap = new Map();
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');
console.log(myMap.get('key1')); // Output: 'value1'
Set:
-
Unique Values:
- A Set is a collection of unique values. It does not allow duplicate values.
-
No Key-Value Pairs:
- Unlike Map, Set does not have key-value pairs. It only contains individual values.
-
Ordering:
- The order of elements in a Set is based on the order in which they were inserted.
-
Methods:
- Sets provide methods for adding, deleting, and checking the presence of values.
- Examples of Set methods include
add(),delete(), andhas().
// Example of a Set
let mySet = new Set();
mySet.add('value1');
mySet.add('value2');
console.log(mySet.has('value1')); // Output: true
Choosing Between Map and Set:
- Use a Map when you need to associate a value with a specific key and you have a logical key-value relationship.
- Use a Set when you need to store a collection of unique values and the order of insertion matters.
In summary, while both Map and Set are useful for managing collections of data in JavaScript, their differences in terms of key-value pairs and uniqueness of values make them suitable for different scenarios.