Middle+
What are Map and Set, and how do they differ?
sobes.tech AI
Answer from AI
Map and Set are built-in data structures in JavaScript (and Node.js) designed for storing collections of data with specific properties.
Map is a collection of key-value pairs, where keys can be of any type (objects, primitives, etc.). Unlike a regular object, Map preserves the insertion order of elements and provides methods for convenient manipulation.
Set is a collection of unique values of any type. Duplicates are not allowed in Set, and it also maintains insertion order.
Main differences:
- Map stores key-value pairs, Set only stores unique values.
- In Map, keys can be of any type; in Set, only values.
- Map has methods
get,set,has,delete, while Set hasadd,has,delete.
Example usage:
const map = new Map();
map.set('key1', 'value1');
map.set({}, 'value2');
console.log(map.get('key1')); // 'value1'
const set = new Set();
set.add(1);
set.add(2);
set.add(1); // will not be added again, since 1 already exists
console.log(set.has(1)); // true