Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m
Ecma 1
  • Overview
  • Transcript

4.2 Maps

Map is a new JavaScript built-in data structure that works similarly to an Object–mapping keys to values. Unlike Objects, though, Maps allow keys to be objects of any type. In this lesson, I’ll show you how to get started with ES6 maps.

4.2 Maps

Hi folks. In this lesson we're going to take a look at another new type of data structure in ES6, the map. Maps are similar to sets which we look at in the last lesson except for the fact that maps store key value pairs instead of individual values. Let's take a look. Like with sets, we need to use a constructor to create a map. There is no literal form. To create a map that contains data, we can pass a two-dimensional array to the map constructor. The first element in each array will be a key in the map. And the second element will be the value associated with that key. As you can see the keys as well as the values can be of any type. Here we have a string as the first key and a number as the second key. Let's just take a look how that is expressed in the browser. Maps have a very similar API to sets but with some key differences. So first let's look at the methods that map has and which the set doesn't. To add a new key value key to the map, we need to use the set method. This method takes two parameters, the key and the value to set. The set method returns the map objects and so it can be chained. So this method works in the same way as the set objects at method. Unlike with this set, we can retrieve a single value from the map without iterating it. We use the get method to do this, specifying the key whose value we want to get as a parameter. The rest of the map API is pretty much the same as the set. We can use the has method to see whether the map contains a given key. In this case the method returns false because our map doesn't have a key called oops. The map can also return iterators, and has several methods for this, which it shares with sets. For example, the entries and values methods. The maps also feature the keys method to return an iterator containing just the keys from the map. Again, we'll be looking at iterators in more detail later in this section, so we won't dwell on them here. So in this lesson we looked at the new map object in year six, and saw that it is similar to the new set object, but that it contains key value pairs instead of individual values. We saw that the maps API is very similar to the set API, except that it uses the set method to add a new key value pair. And that we can also use the get method to retrieve individual values, without iterating the map. Thanks for watching.

Back to the top