Map

An object data structure used to track a collection of key-value pairs. Internally repesented as a hash table.


Construction

new Map();
Map(0) {}

You may pass an iterable to the constructor.

new Map([
  ['foo', 1],
  ['bar', 2]
]);
Map(2) { 'foo' => 1, 'bar' => 2 }

Get

const map = new Map();
map.set(1, 'a')
map.get(1);
'a'
map.get('a');
undefined

Set

const map = new Map();
map.set('hello', 'world');
Map(1) { 'hello' => 'world' }

Remove

const map = new Map([
  ['foo', 1]
]);
map.delete('foo');
true
map.delete('foo');
false
map;
Map(0) {}

Check Membership

const map = new Map([
  ['key', 'val']
]);
map.has('key');
true
map.has('val');
false

Member Count

const map = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 3]
]);
map.size;
3

Iterating

A map is iterable in insertion order.

const map = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 3]
]);
for (const [key, val] of map) {
  console.log(key, val);
}
a 1
b 1
c 1
[...map];
[['a', 1], ['b', 2], ['c', 3]]
[...map.keys()]
['a', 'b', 'c']
[...map.values()]
[1, 2, 3]

A map also exposes a forEach function.

const map = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 3]
]);
map.forEach(val => console.log(val));
1
2
3

External Resources