Map and Set in JavaScript
Source: Dev.to
What Is a Map?
A Map is a collection of key‑value pairs, similar to an object, but with several improvements:
- Keys can be any type (objects, functions, primitives)
- Preserves insertion order
- Built‑in methods to get, set, delete, and check entries
Map Example
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); // 3Map Visual
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
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
[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
const numbers = [1, 2, 3, 2, 4, 3];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4]Map for Counting Occurrences
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
- Both solve common limitations of objects and arrays.