© Russ Ferguson and Keith Cirkel 2017

Russ Ferguson and Keith Cirkel, JavaScript Recipes, 10.1007/978-1-4302-6107-0_11

11. Working with Maps

Russ Ferguson and Keith Cirkel2

(1)Ocean, New Jersey, USA

(2)London, UK

What Are the Advantages of Using a Map over an Object?

Problem

When is it better to use a map rather than an object?

Solution

While there are similarities to maps and objects, maps can contain both objects and primitives as keys or values.

The Code

Listing 11-1. Maps Can Use Different Types as Keys, Whereas Objects Use Strings
var mapObj = new Map();    mapObj.set('myString', 'myString is a string key');    console.log(mapObj.get('myString')); //myString is a string keyvar myObj = {};    mapObj.set(myObj, 'Object is a used as a key');    console.log(mapObj.get(myObj)); ...

Get JavaScript Recipes: A Problem-Solution Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.