4 min read
•Question 27 of 50mediumWhat are Set and Map in JavaScript?
Understanding Set and Map data structures.
What You'll Learn
- Set for unique values
- Map for key-value pairs
- When to use each
Set
A collection of unique values.
code.jsJavaScript
// Creating a Set
const set = new Set([1, 2, 3, 3, 4]);
console.log(set); // Set { 1, 2, 3, 4 }
// Methods
set.add(5);
set.has(3); // true
set.delete(2);
set.size; // 4
set.clear();
// Remove duplicates from array
const arr = [1, 2, 2, 3, 3, 3];
const unique = [...new Set(arr)]; // [1, 2, 3]
// Iteration
for (const value of set) {
console.log(value);
}Map
A collection of key-value pairs with any type as key.
code.jsJavaScript
// Creating a Map
const map = new Map();
map.set('name', 'John');
map.set(1, 'one');
map.set({ key: 1 }, 'object key');
// Object as key
const userRoles = new Map();
const user = { id: 1 };
userRoles.set(user, 'admin');
userRoles.get(user); // 'admin'
// Methods
map.get('name'); // 'John'
map.has('name'); // true
map.delete('name');
map.size; // 2
// Iteration
for (const [key, value] of map) {
console.log(key, value);
}Map vs Object
| Feature | Object | Map |
|---|---|---|
| Key types | String/Symbol | Any |
| Order | Not guaranteed | Insertion order |
| Size | Manual count | .size property |
| Iteration | Indirect | Direct |