In the previous archive, we learnt that standard Objects have a fatal flaw. They implicitly convert all keys to Strings. ES6 introduced proper data structures to solve this architectural limitation.
A Map is a collection of keyed data items, similar to an Object. However, the main difference is that Map allows keys of any type.
{} are treated as two unique keys.Example:
let map = new Map();
let user = { name: "Singh" };
// Using an Object as a key
map.set(user, "Architect");
console.log(map.get(user)); // "Architect"
console.log(map.size); // 1A Set is a special collection of set of values (without keys) where each value may occur only once.
set.has(value) is significantly faster (O(1)) than searching an Array arr.includes(value) (O(N)).Example:
let mySet = new Set();
mySet.add(1);
mySet.add(5);
mySet.add(1); // Ignored (Duplicate)
console.log(mySet.size); // 2| Feature | Object | Map | Set |
|---|---|---|---|
| Concept | Record / Dictionary | True Hash Map | Unique List |
| Key Types | Strings / Symbols | Any Type | N/A (Values only) |
| Key Coercion | Yes (Implicit String) | No | N/A |
| Duplicates | Overwrites Key | Unique Keys | Unique Values |
| Iteration | Object.keys() | .keys(), for..of | for..of |
| Size | Manual Count | .size | .size |