In JavaScript, Set and Map are built-in data structures used to store ordered collections of data, where Set holds unique values and Map stores data as key–value pairs.
- Set: Stores a collection of unique values with no duplicates.
- Map: Stores data as key–value pairs, allowing efficient lookup by keys.
JavaScript Set
JavaScript Set is a collection of unique values accessed without keys, where duplicate entries are not allowed.
- Stores only distinct values.
- Commonly used to remove duplicates from other data structures.
let sample = new Set();
sample.add("Hello");
sample.add(1)
sample.add("Bye")
sample.add("@");
for (let item of sample) {
console.log(item);
}
- A new Set named sample is created, and four distinct values are added.
- Iterating over sample with for…of logs each value in the order they were inserted.
Note: Sets store only unique values, so any duplicate additions would be ignored.
Syntax:
new Set([it]);JavaScript Map
Maps are used to store data in key-value pairs where keys are used to uniquely identify an element and values contain the data associated with it.
- Keys can be of any data type.
- Maintains insertion order for entries.
let sample = new Map();
sample.set("name", "Ram");
sample.set("Role", "SDE")
sample.set("Country", "India")
for (let item of sample) {
console.log(item);
}
- A Map is created and key–value pairs are added using set().
- Iteration with for...of prints each entry as [key, value] in order.
Syntax:
new Map([it]);When to Use Set or Map in JavaScript
- The choice between Set and Map depends on how the data needs to be accessed.
- Use Map when data must be identified and retrieved using keys.
- Use Set when only unique values need to be stored.
Difference between Map and set
Here's the difference between Map and Set:
| Map | Set |
|---|---|
| It is a collection of key-value | It is a collection of unique elements |
| Map is two-dimensional | The set is one dimensional |
| Values are accessed using keys | In-built methods are used to access values |