12Maps and Sets

In this chapter, you'll learn about ES2015+'s Maps, Sets, WeakMaps, and WeakSets. Maps store key/value pairs, where the key and value can be (almost) anything. Sets store unique values. WeakMaps are similar to Maps, but the keys are objects and those objects are held weakly (they can be garbage collected, which removes the entry from the map). WeakSets hold unique objects weakly.

MAPS

You often want to create a map of one thing to another, for instance a map of IDs to objects that have that ID. In JavaScript, we've often used (some say abused) objects for that. But since it's not what objects are designed for, there are some pragmatic issues with using objects for generic maps:

  • The keys can only be strings (or Symbols as of ES2015).
  • Until ES2015, you couldn't count on the order if you needed to loop through the entries in the object; and as you learned in Chapter 5, even though ES2015 added order, relying on it isn't usually a good idea because the order depends on both the order the properties were added to the object and the form of the property key (strings in the canonical integer index form come first, numerically).
  • Objects are optimized by JavaScript engines on the assumption that they mostly only have properties added ...

Get JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.