Maps

new Map([ ["key1", "val1"], ["key2", "val2"], ["key3", "val3"] ])
     .set("key10", "val10")
     .forEach(function(v,k,m) {
        console.log(`key = ${k} value = ${v}`); 
      });

Map

The Map object holds key-value pairs (entries) and remembers the original insertion order of the keys. It looks like an object’s properties, but

  • does not contain any keys by default
  • keys can be any value including function, not only String
  • keys are stored in order of insertion
  • propertysize allows to retrieve number of items
  • a Map object is iterable
  • a Map object is faster when items are frequently added or removed
methoddescription
set(k, v) Sets value for the key. Returns map object.
get(k) Returns value associated with given key or undefined value if no element with this key.
has(k) Returns true if entry with given key exist.
forEach(cb [, thisArg]) Executes callback function for every entry. Callback functions has 3 parameters:
  • val - value of entry
  • key - key of entry
  • map - map itself
thisArg parameter provides a this value for callback function.
entries() Returns iterator for iterating over all entries (pair of key and value) of map.
values() Returns iterator for iterating over all values of map in insertion order.
keys() Returns iterator for iterating over all keys of map in insertion order.
clear() Removes all entries from map.
delete(key) Removes element with key. Returns false if element with given key does not exist.

WeakMap

The WeakMap object is a collection of key/value pairs (entries) in which the keys are weakly referenced. So only objects allowed as a key, not primitive values. When key not used anywhere, entry will be removed by garbage collector. So you can't iterating over elements.

WeakMap has only 4 methods: delete(key), get(key), has(key), set(key, value). Property length is always 0 value.