Middle+
Tell about collections Map and Set in JavaScript — what do you know about them?
sobes.tech AI
Answer from AI
Map and Set are collections in JavaScript introduced in ES6 that extend data handling capabilities compared to regular objects and arrays.
Map is a collection of key-value pairs where keys can be of any type (objects, functions, primitives). Unlike regular objects, Map preserves the insertion order of elements and has convenient methods for working:
set(key, value)— add or update an elementget(key)— retrieve a value by keyhas(key)— check for the presence of a keydelete(key)— remove an elementsize— number of elements
Example:
const map = new Map();
map.set('a', 1);
map.set({}, 2);
console.log(map.get('a')); // 1
console.log(map.size); // 2
Set is a collection of unique values of any type. It automatically excludes duplicates and maintains insertion order:
add(value)— add an elementhas(value)— check for presencedelete(value)— remove an elementsize— number of elements
Example:
const set = new Set();
set.add(1);
set.add(1);
set.add('text');
console.log(set.size); // 2
Both collections support iteration, which is convenient for traversing elements.