Sobes.tech
Middle+

What is preferable for storing data by key: Map or a regular object? What are the advantages of Map?

sobes.tech AI

Answer from AI

To store data by key in JavaScript, you can use either a regular object ({}) or a Map. It is preferable to use a Map in the following cases:

  • Keys can be not only strings or symbols but also objects or other types.
  • You need to guarantee the insertion order of elements (Map preserves order).
  • Efficient addition, deletion, and key existence checks are required.
  • You want to avoid issues with inherited properties of the prototype (they exist in objects, but not in Map).

Advantages of Map:

  • Supports any types of keys.
  • Methods set, get, has, delete for convenient work.
  • Iteration over Map occurs in insertion order.

Example:

const map = new Map();
const objKey = { id: 1 };

map.set(objKey, 'value');
console.log(map.get(objKey)); // 'value'

// This cannot be done with an object; the key will be converted to the string '[object Object]'
const obj = {};
obj[objKey] = 'value';
console.log(obj[objKey]); // 'value', but the key is a string

Thus, Map is more versatile and safer for storing data by key, especially if the keys are not strings.