Maps and Sets

Map is a built-in data structure for efficiently storing key-value pairs, and Set is a built-in data structure for efficiently storing collections of unique values.

Unlike regular objects, which require keys to be strings, a Map allows you to use any type of value as a key.

Creating a Map

You can initialize a Map instance with new Map.

A Map can be initialized with an array of tuples, which correspond to the key-value pairs in the map.

The example above also illustrates one unique feature of Map that makes it more suitable for working with mappings.

When using numeric keys with standard objects, there can be a mismatch between inferred types and actual values, since object keys are always strings. A Map instance will always represent numeric keys in the form of a number.

Modifying a Map

The set method adds a new key-value pair to a Map instance, and the get method returns the value corresponding to a given key.

You can delete

Iterating over a Map

You can use a for loop to iterate over each key-value pair in a Map instance.

  • The keys method
  • The values method
  • The entries method

Object keys

Map

Map maintains the insertion order of elements.

Was this page helpful?