ES6: Create, modify and interact with Maps in JavaScript

In this post we're going to take a look at a new data structure introduced in ES6 called Map.

The Map data structure is probably familiar to most people out there, either from other languages or the similarities to the JavaScript object literal.

Now let's dive into how JavaScripts version of the Map works and how we can use it.

Creating a Map

Let's start with the absolute basic — creating an empty Map.

new Map();  
//> {}

That's it! We got ourselves an empty Map.

Now, an empty Map doesn't make much sense, so let's add some data to it.

We got two options.

Either we add values during initialization.

new Map([['name','Luke'],['age','32'],['city','New York']]);  

Or we can add values after initialization using the Map.set method.

new Map().set('name','Luke').set('age','32').set('city','New York');  

The reason for us being able to chain the add methods this way, is because the add function returns the object it's modifying.

It's important to be aware that the add method doesn't return a new object in an immutable fashion, but is only returning a reference to the same object.

What are valid keys and values?

An interesting thing about the Map data structure in JavaScript is that it accepts both objects and primitives as key and values.

// Primitives
new Map([['name' , 'Luke'],[10,'ten'],[true,'The truth!']]);

// Objects
new Map([[{'key': 'name'},{'value': 'Luke'}]]);  

Now, a key in a Map needs to be unique, but that begs the question — How does the Map define uniqueness?

The uniqueness of a key is tested using a strict equal ===, except for NaN which is equal even if NaN !== NaN.

So, if we test these primitives, we pretty much get what we expect.

const primitives = new Map([['name','Luke'],[10,'ten'],[true,'The truth!']]);

primitives.get('name');  
// > 'Luke'

primitives.get(10);  
// > 'ten'

primitives.get(true);  
// > 'The truth'

Great, but what if the keys are objects?

const key = {'key': 'name'};  
const person = new Map([[key, 'Luke']]);

person.get(key);  
// > 'Luke'

person.get({'key': 'name'});  
// > undefined

As you can see, the equality is tested by object reference, meaning it's not good enough to provide an object that has the same content.

Interacting with a Map

The Map object got lots of different methods to help us interact with it.

Checking if a Map contains a certain key

If we want to check if a Map contains a certain key, all we need to do is to use the has function.

const person = new Map([['name' , 'Luke'],['age','32'],['city','New York']]);

person.has('name');  
//> true
person.has('hobby');  
//> false

Getting a value based on the associated key

If you want to get a value using the associated key, you simply use the get function as we used when we looked at uniqueness earlier in this post.

const person = new Map([['name' , 'Luke'],['age','32'],['city','New York']]);

person.get('name');  
//> 'Luke'  

So what happens if the there aren't any entries in the Map for a given key? In that case undefined will be returned.

const person = new Map([['name' , 'Luke'],['age','32'],['city','New York']]);

person.get('hobby');  
//> undefined  

Extracting the keys from a Map

To extract keys from a Map, we can use the keys function.

const person = new Map([['name' , 'Luke'],['age','32'],['city','New York']]);

person.keys();  
//> ['name', 'age', 'city']

Extracting the values from a Map

The same goes for the values - a simple call to the values function will give you the values of the Map.

const person = new Map([['name' , 'Luke'],['age','32'],['city','New York']]);

person.values();  
//> ['Luke', '32', 'New York']

Deleting entries in a Map

Deleting entries is as easy as the preceding operations.

You can delete one entry by key using the delete function.

const person = new Map([['name' , 'Luke'],['age','32'],['city','New York']]);

person.delete('city');  
//> true

delete returns true to indicate that it found the entry and deleted it.

If the key doesn't exist in the Map, it'll return false.

Another option is to delete all entries in the Map using the clear function.

const person = new Map([['name' , 'Luke'],['age','32'],['city','New York']]);

person.clear();  

Iterating a Map

Iterating a Map can easily be done in one of two ways.

Either you can use a for loop.

for (let [key, value] of person) {  
    console.log(key, value);
}

// > name Luke
//   age 32
//   city New York

or you can use the forEach method.

person.forEach((value, key) => console.log(key, value));

// > name Luke
//   age 32
//   city New York