Middle+
What are Map and Set, how do they differ, and what are their features?
sobes.tech AI
Answer from AI
Map and Set are collections in JavaScript designed for storing data, but with different purposes:
-
Map is a collection of key-value pairs. Keys can be of any type (objects, functions, primitives). Map maintains the order of insertion.
-
Set is a collection of unique values. It cannot contain duplicates, and it also maintains the order of insertion.
Differences and features:
- Map stores key-value pairs, Set stores only values.
- In Map, you can quickly get a value by key; in Set, you check for the presence of a value.
- Map has methods
set(key, value),get(key),has(key),delete(key),size. - Set has methods
add(value),has(value),delete(value),size.
Example:
const map = new Map();
map.set('a', 1);
map.set({}, 2);
const set = new Set();
set.add(1);
set.add(2);
set.add(1); // will not be added again, as it's a duplicate
console.log(map.get('a')); // 1
console.log(set.has(2)); // true