Sobes.tech
Junior — Middle

Explain what a Map data structure in JavaScript is and how it differs from regular objects.

sobes.tech AI

Answer from AI

In JavaScript, the Map data structure is a collection of key-value pairs where keys can be of any type (objects, functions, primitives). Unlike regular objects, where keys are strings or symbols, Map allows using any values as keys.

Main differences between Map and object:

  • Keys in Map can be of any type, not just strings or symbols.
  • Map preserves the insertion order of elements.
  • Map has built-in methods: set(), get(), has(), delete(), clear().
  • Map has a size property to get the number of elements, whereas for objects, you need to count keys manually.

Example of using Map:

const map = new Map();

const objKey = { id: 1 };
map.set(objKey, 'value for object');
map.set('key', 123);

console.log(map.get(objKey)); // 'value for object'
console.log(map.get('key')); // 123
console.log(map.size); // 2

Thus, Map is convenient when keys are not only strings, and when the order of elements and performance during frequent add and search operations are important.