JavaScript Maps - patrickcole/learning GitHub Wiki

JavaScript Maps

a Map is an iterable keyed collection that remembers the original insertion order of the keys.

Unlike plain objects that only allow Strings to be the keys, a Map can have any primitive as a key.

Here's an example of trying to use a Number as a key for an object:

let chapters = {
  1: 'beginning',
  2: 'act 1',
  3: 'act 2',
  4: 'act 3',
  5: 'conclusion'
}

Being that this is a regular Object, JavaScript will convert the numeric keys into strings, so they conform to the pattern.

Map keys can be set with any primitive:

let chaptersMap = new Map();
chaptersMap.set(1, 'beginning');
chaptersMap.set(2, 'act1');
// etc...

// now testing the keys:
console.log([...chaptersMap.keys()]); // => [1,2]

You can also use types such as booleans, but then you would only have two keys: true and false.

WeakMaps

  • Accept objects as keys, and only objects
  • Designed to remove complexity and reduce memory leaks for this pattern
const foo = { name: 'foo' };
const bar = { name: 'bar' };

const mapOfObjects = new WeakMap();

mapOfObjects.set(foo, 'Foo related data');
mapOfObjects.set(bar, 'Bar related data');

mapOfObjects.get(foo); // => 'Foo related data'

Key Name Rules

  • There are no restrictions for naming keys in a map
  • unlike regular objects, which should not have keys such as toString remapped, because that's really dangerous

Maps Are Iterable

const colorsHexMap = new Map();

colorsHexMap.set('white', '#FFFFFF');
colorsHexMap.set('black', '#000000');

for (const [color, hex] of colorsHexMap) {
  console.log(color, hex);
}
// => 'white' '#FFFFFF'
// => 'black' '#000000'
  • can also use map.keys() to return iterator of keys
  • map.values() also returns iterator of the values

Map Size is More Distinct

  • plain objects size can be misleading as there are hidden key/value pairs that exist
  • with plain objects, using something such as Object.keys() works, but the method is not designed to get the size
  • maps have a dedicated method: Map.size()

Source