Map and Set
Map stores key-value pairs and allows keys of any value type. Unlike ordinary objects, a Map does not convert keys to strings. Set stores unique values and is useful for membership checks and deduplication.
Maps and Sets are often preferable to objects and arrays when their semantics match the problem.
Map and Set
const users = new Map();
users.set(101, { name: 'Suriya' });
const ids = new Set([1, 1, 2, 3, 3]);
console.log(users.get(101));
console.log([...ids]);💡 Map preserves the numeric key 101 as a numeric key. Set automatically keeps only unique values.
Key Takeaways
- Map supports arbitrary key types.
- Set stores unique values.
- Use collection types according to the semantics you need.
Knowledge Check
What is a key advantage of Map over a plain object?