JavaScript Maps

Head’s up! In the next video we are going to make use of a few different functions from the JavaScript built in Map object. Let’s review!

Maps are like regular JavaScript Objects. Just like we create Objects with:

const capitalCities = {};
capitalCities.japan = "Tokyo";
capitalCities.india = "New Delhi";

We create Maps with:

const capitalCities = new Map();
capitalCities.set("japan", "Tokyo");
capitalCities.set("india", "New Delhi");

Both let you assign values to keys and get those values.

capitalCities.get("japan");
=> Tokyo

To detect if a value exists in a Map:

capitalCities.has("canada")
=> false

We can log the values of the cities by using the values() iterator:

for (const city of capitalCities.values()) {
  console.log(city);
}

One of the key differences between Maps and Objects is that Maps preserve the order of insertions. You’ll always get back the cities in the order you put them in!

Finally, we can get an ordered Array from our values() iterator using the built in Array.from function:

Array.from(capitalCities.values());
=> [ "Tokyo", "New Delhi” ]

Phew! That wasn't so bad. And now we're ready to jump in to the next video!