JavaScript offers Map and Set as modern data structures to solve common problems with traditional objects and arrays.
Letβs explore what they are, how they differ, and when to use them.
π§ What Is a Map?
A Map is a collection of key-value pairs, similar to an object, but with some improvements:
- Keys can be any type (objects, functions, primitives)
- Preserves insertion order
- Built-in methods to get, set, delete, and check entries
β Map Example
```js id="map1"
const map = new Map();
map.set("name", "Rahul");
map.set("age", 22);
map.set(true, "Boolean key");
console.log(map.get("name")); // Rahul
console.log(map.has("age")); // true
console.log(map.size); // 3
---
### π Map Visual
```id="viz1"
Key β Value
"name" β "Rahul"
"age" β 22
true β "Boolean key"
β‘ Map vs Object
| Feature | Map | Object |
|---|---|---|
| Key types | Any type | String / Symbol |
| Order preservation | Yes | Not guaranteed |
| Size property | map.size |
Must compute manually |
| Iteration | Built-in | Manual / Object.keys |
π§ What Is a Set?
A Set is a collection of unique valuesβduplicates are automatically removed.
- Can store any type of value
- Provides fast lookups and uniqueness checks
β Set Example
```js id="set1"
const set = new Set([1, 2, 3, 2, 1]);
console.log(set); // Set(3) { 1, 2, 3 }
console.log(set.has(2)); // true
set.add(4);
console.log(set); // Set(4) { 1, 2, 3, 4 }
---
### π Set Visual
```id="viz2"
[1, 2, 3, 2, 1] β Set β {1, 2, 3}
β‘ Set vs Array
| Feature | Set | Array |
|---|---|---|
| Uniqueness | β Unique values | β Allows duplicates |
| Lookup speed | Fast | Linear search |
| Methods | add, delete, has | push, pop, includes |
π οΈ When to Use Map and Set
Use Map when:
- You need dynamic keys of any type
- You want ordered key-value storage
- You need built-in iteration over entries
Use Set when:
- You want unique values only
- You need to quickly check existence
- You want to remove duplicates from an array
πΉ Removing Duplicates Example
```js id="set2"
const numbers = [1, 2, 3, 2, 4, 3];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4]
---
### πΉ Map for Counting Occurrences
```js id="map2"
const arr = ["apple", "banana", "apple"];
const countMap = new Map();
arr.forEach(item => {
countMap.set(item, (countMap.get(item) || 0) + 1);
});
console.log(countMap);
// Map(2) { "apple" => 2, "banana" => 1 }
β‘ Key Takeaways
- Map β flexible key-value storage, ordered, keys can be any type
- Set β collection of unique values, fast lookups, removes duplicates easily
- Solves common limitations of Objects and Arrays
Top comments (0)