Sobes.tech
Middle+

What is the difference between Map and WeakMap?

sobes.tech AI

Answer from AI

Map and WeakMap are key-value collections in JavaScript, but they have important differences:

  • Keys:

    • In Map, keys can be any values, including primitives.
    • In WeakMap, keys must be objects (non-primitives).
  • Garbage collection:

    • Map holds strong references to keys and values, so objects used as keys will not be garbage collected as long as they are in the Map.
    • WeakMap holds weak references to keys, meaning if an object key is no longer used elsewhere, it can be garbage collected, and the corresponding entry in WeakMap will disappear automatically.
  • Iteration:

    • Map supports iteration methods (e.g., map.forEach, map.keys(), map.values()).
    • WeakMap does not support iteration because its contents can change due to garbage collection at any moment.

Example of using Map and WeakMap:

const map = new Map();
const weakMap = new WeakMap();

const objKey = { id: 1 };

map.set(objKey, 'value in Map');
weakMap.set(objKey, 'value in WeakMap');

console.log(map.get(objKey));      // 'value in Map'
console.log(weakMap.get(objKey)); // 'value in WeakMap'

// If objKey is no longer used elsewhere, the entry in WeakMap can be automatically removed.

WeakMap is useful for storing data associated with objects without the risk of memory leaks.