O'Reilly logo

Learning JavaScript, 3rd Edition by Ethan Brown

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 10. Maps and Sets

ES6 introduces two welcome data structures: maps and sets. Maps are similar to objects in that they can map a key to a value, and sets are similar to arrays except that duplicates are not allowed.

Maps

Prior to ES6, when you needed to map keys to values, you would turn to an object, because objects allow you to map string keys to object values of any type. However, using objects for this purpose has many drawbacks:

  • The prototypal nature of objects means that there could be mappings that you didn’t intend.

  • There’s no easy way to know how many mappings there are in an object.

  • Keys must be strings or symbols, preventing you from mapping objects to values.

  • Objects do not guarantee any order to their properties.

The Map object addresses these deficiencies, and is a superior choice for mapping keys to values (even if the keys are strings). For example, imagine you have user objects you wish to map to roles:

const u1 = { name: 'Cynthia' };
const u2 = { name: 'Jackson' };
const u3 = { name: 'Olive' };
const u4 = { name: 'James' };

You would start by creating a map:

const userRoles = new Map();

Then you can use the map to assign users to roles by using its set() method:

userRoles.set(u1, 'User');
userRoles.set(u2, 'User');
userRoles.set(u3, 'Admin');
// poor James...we don't assign him a role

The set() method is also chainable, which can save some typing:

userRoles
   .set(u1, 'User')
   .set(u2, 'User')
   .set(u3, 'Admin');

You can also pass an array of arrays ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required