New Built-in Classes: Map

Learn about the basics of the JavaScript’s new built-in class, maps.

Using Map

Associative maps or dictionaries are significant data structures in programming. You may have used Map in Java or Dictionary in C#, for example. Suppose you want to keep track of teams and scores during the sports season.

Why were maps introduced in JavaScript?

A map will make it easy to create and update the score values and also to look up the scores based on a team’s name. It’s hard to believe that we can seriously program without maps.

Since an object in JavaScript has keys and values and there was no special Map type, programmers often used simple objects to represent maps in the past. Unfortunately, this resulted in a few problems.

  1. For one, there was no foolproof way to iterate over the keys; the keys() method converted fields to strings, resulting in the accidental collision of keys.
  2. There was no easy way to add new keys and values; in short, using a generic object to represent a map was not intuitive or elegant. The new Map type in JavaScript fixes that issue.

Definition: A Map is an associative collection of keys and values where the keys are distinct. Keys and values may be any primitive or object.

We can create an empty map and add values to it, or we can create it with some initial values.

Playing with maps

Let’s create a Map of names as the key and some scores as values.

Get hands-on with 1400+ tech skills courses.