JavaScript Map and Set - Beginner Concepts
------------------------------------------
1. What is a Map?
- A Map is a collection of key-value pairs.
- Keys can be any type.
- Maintains insertion order.
Example:
const map = new Map();
map.set("name", "Alice");
map.set(100, "Score");
map.set(true, "Passed");
map.get("name"); // "Alice"
map.size; // 3
map.has(100); // true
Loop:
for (let [key, value] of map) {
console.log(key, value);
}
------------------------------------------
2. What is a Set?
- A Set is a collection of unique values.
- No duplicate values allowed.
- Maintains insertion order.
Example:
const set = new Set();
set.add(1);
set.add(2);
set.add(2); // ignored
set.has(2); // true
set.size; // 2
Loop:
for (let value of set) {
console.log(value);
}
------------------------------------------
Map vs Object
| Feature | Map | Object |
|-----------------|-------------------|----------------------|
| Key types | Any type | String/Symbol only |
| Order preserved | Yes | Not guaranteed |
| Size property | .size | Object.keys().length |
------------------------------------------
Set vs Array
| Feature | Set | Array |
|------------------|-------------------|---------------------|
| Duplicates | Not allowed | Allowed |
| Existence check | .has() | .includes() |
| Uniqueness | Ensured | Must check manually |
------------------------------------------
Use Cases
Use Map:
- Need key-value pairs with any key type
- Maintain insertion order
- Frequent lookup/update
Use Set:
- Remove duplicates
- Fast existence check
- Store unique values
Example: Remove duplicates from array
const arr = [1, 2, 2, 3, 4, 4];
const unique = [...new Set(arr)];
console.log(unique); // [1, 2, 3, 4]