Lesson 25. Maps

 

After reading lesson 25, you will

  • Know to create a Map
  • How to convert a plain object into a Map
  • How to add and access values on a Map
  • How to iterate the keys and values from a Map
  • How Maps are destructured
  • Understand when it makes sense to use a Map over an Object
  • Understand why it makes sense to use a WeakMap over a Map

Like Sets, Maps are a new type of object in JavaScript. Not to be confused with Array.prototype.map, which is a higher-order array method, Maps are another type of iterable that’s new to JavaScript in ES2015. A Map is a lot like a generic object in JavaScript with keys and values. But a Map can be iterated, whereas an object can’t. Plain objects are also limited to only being able to have string values as keys;[1] Maps, on the other hand, can have any datatype as a key, even another Map!

1Technically, strings and symbols.

Consider this

When you need a container of data with no need for qualified identifiers for each datum, you may reach for an array. When you need to store data and be able to retrieve specific data based on a string identifier, you may reach for an object. But what if you need to retrieve data based on a more complex identifier such as a DOM node or something else that can’t be used as the key of an object? What do you reach for then?

25.1. Creating maps

As with Sets, there’s no literal version of a Map and they must be created using the new keyword like so:

const myMap = new Map();

25.2. Using maps

25.3. When to use maps

25.4. What about the WeakMap?

Summary