Map (and WeakMap)

A Map is quite similar to an Object. See the following for the differences:

Object Map WeakMap
key String /
Symbol
any value Object
.size (none) supported (none)
getter / setter . [] etc. .get()
.set()
.get()
.set()
reference bindings strong strong weak
iterable? No Yes No

A WeakMap is a map where the keys are weak. If all references to the key are lost and there are no more references to the value, the value can be garbage collected, preventing memory leak. A WeakMap is not enumerable, and can thus be used for encapsulation and information hiding.A Map has the following methods:

Map.prototype.clear()

Removes all key/value pairs from the Map object.

Map.prototype.forEach(callbackFn[, thisArg])

Calls callbackFn once for each key-value pair present in the Map object, in insertion order. If a thisArg parameter is provided to forEach, it will be used as the 'this' value for each callback.

The following four methods are also shared by WeakMap.

Map.prototype.has(key)

Returns a boolean asserting whether a value has been associated to the key in the Map object or not.

Map.prototype.get(key)

Returns the value associated to the key, or undefined if there is none.

Map.prototype.set(key, value)

Sets the value for the key in the Map object. Returns the Map object.

Map.prototype.delete(key)

Removes any value associated to the key and returns the value that Map.prototype.has(key) would have previously returned. Map.prototype.has(key) will return false afterwards.

This illustrates how to convert a plain object to a Map.
RESETRUNFULL
<!DOCTYPE html><html><body><script>

var o = {a:1,b:2};var m = new Map(Object.entries(o));                                           // new Map([["a", 1],["b", 2]]);for (v of m) console.log(v);  // ["a", 1] ["b", 2]

</script></body><html>

For information about the following three methods, refer to 8.12.4.

Map.prototype.keys()

Map.prototype.values()

Map.prototype.entries()


RESETRUNFULL
<!DOCTYPE html><html><body><script>

var m = new Map();var keyString = 'a string',
      keyObj = {},
      keyFunc = function() {};m.set(keyString, 1);m.set(keyObj, 2);m.set(keyFunc, 3);m.set(NaN, 4);m.size; // 4// getting the valuesm.get(keyString);    // 1m.get(keyObj);       // 2m.get(keyFunc);      // 3m.get('a string');   // 1 because keyString === 'a string'm.get({});           // undefined, because keyObj !== {}m.get(function() {})                // undefined, because keyFunc !== function () {}m.get(NaN);          // 4

</script></body><html>

RESETRUNFULL
<!DOCTYPE html><html><body><script>

var wm = new WeakMap([[{},2],[{},{}],[{},[]]]);wm.has({}); // false

</script></body><html>