Maps

Map

Is an object that stores any set of key => value of any kind of data type.

Different from a object that stores only string | Symbol keys.

Atention: May result in memory leaks, if elements are not properly handled.

  • Since references to the keys might be lost, and the values inside the the Map will remain.

const timeUnits = new Map(
    ["second", 1],
    ["minute", 60],
    ["hour", 3600]
);

// Convert the Map back to array
Array.from(timeUnits);

.size: Returns the amount of pairs.

.set(key, value): Add a key => value pair.

.forEach(fn): Iterates over the Map fn(value, key) => {}.

.has(key): Returns true | false if a given key exists.

.get(key): Returns the value | undefined of a given key.

.delete(key): Removes a pair key => value of given key, and returns true | false.

.clear(): Remove all the elements.

Weak Map

Similar to Map, but allows only keys of type object.

  • Maintain the references in a weak way.

    • This is because if the reference to the object, which is a key, is lost, it is not possible anymore to access the value.

  • Not Iterable.

They can be usefull for cache implementations.

.set(key, value): Add a key => value pair.

.has(key): Return true if key exists.

.get(key): Return the value of a given key.

.delete(key): Removes a pair given a key.

Last updated