Middle+
What is the difference between Map and Set in JavaScript?
sobes.tech AI
Answer from AI
Map and Set are collections in JavaScript, but they serve different purposes:
-
Map is a collection of key-value pairs. Keys can be of any type (objects, primitives). Map maintains the insertion order of elements and allows quick retrieval of values by key.
-
Set is a collection of unique values. It stores only unique elements, without keys, and also maintains the insertion order.
Example:
const map = new Map();
map.set('key1', 'value1');
map.set({}, 'value2');
const set = new Set();
set.add('value1');
set.add('value2');
set.add('value1'); // will not be added again, as it already exists
console.log(map.get('key1')); // 'value1'
console.log(set.has('value1')); // true
Summary:
- Map — for storing key-value pairs.
- Set — for storing unique values without keys.