Sobes.tech
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 element
  • get(key) — retrieve a value by key
  • has(key) — check for the presence of a key
  • delete(key) — remove an element
  • size — 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 element
  • has(value) — check for presence
  • delete(value) — remove an element
  • size — 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.

Tell about collections Map and Set in JavaScript… - sobes.tech