liveBook · Manning

Map

As explained in Secrets of the JavaScript Ninja, Second Edition

A collection type that stores key-value associations and supports efficient lookup by key.

A Map stores associations between keys and values, making it useful for dictionary-style lookups. In JavaScript, the built-in Map collection avoids pitfalls that make plain objects unreliable as maps. section 9.2 section 9.4

Why plain objects can fail as maps:

  • Objects inherit properties such as constructor, so a missing dictionary entry can return an inherited property instead of undefined. section 9.2.1
  • Object keys are strings: using different HTML elements as keys can convert them to the same string and overwrite an association. section 9.2.1

Translations and DOM data

A localization dictionary can associate phrases with translations. A Map is also a better fit than a plain object for attaching data to HTML elements; Maps can be iterated with for...of. section 9.2 section 9.2.1 section 9.4

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains prototype-property and key-coercion pitfalls through examples, recommends Map, and stops short of detailing its API.
Examples
Uses a localization dictionary, an inherited constructor lookup, and HTML elements whose object keys collide after string conversion.
What you can do after
Apply JavaScript’s built-in Map instead of a plain object when prototype properties or non-string keys could disrupt lookups.
How it connects
Connects maps with JavaScript objects, prototypes, DOM nodes, and collection iteration.

Also explained in

Compare how 42 books explain Map →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.