ProgrammingJavascriptCareerProductivityGadgetsASP.NETWeb Design

Working with Maps in ECMAScript 6

Written by
Published on
Filed under
Working with Maps in ECMAScript 6

In my last post I went over the Set() data structure that was introduced with ECMAScript 6. Today I will be going over the Map() data structure, which is similar to a Set(), but brings with it a few slight changes that make it idea for working with certain data sets.

Overview

Map() is an ordered list of key-value pairs where they key and the value can both be of any given type. That implies that "5" and 5 can be considered unique identifiers in a Map().

This is where Maps() differentiate themselves from your typical objects in JavaScript, in which the JS engine will coerce keys to an equivalent string value.

let map = new Map();


map.set("Key1", "Value1");
map.set("Key2", "Value2");
map.set(234, "Value3");

Like with standard objects however, keys must be unique in the collection. So the following would simply override the previous value given for "Key1":

map.set("Key1", "Changed");
map.set("Key1", "Changed again");

Getting and setting values

Retrieving the values back from a Map() is done using the associated get() method:

let map = new Map();


map.set("Key1", "Value1");
map.set(234, "Value2");


console.log(map.get("Key1"));	// Value1
console.log(map.get(234));	// Value2
console.log(map.get("NotAKey")); // undefined

If you attempt to retrieve a key that is not in the collection, JavaScript will return a value of undefined.

Objects as keys

One interesting feature of Maps, is that you can use objects as key values:

let map = new Map();
let obj1 = {};
let obj2 = {};


map.set(obj1, "Val1");
map.set(obj2, "Val2");


console.log(map.get(obj1));

How can you use this feature? If you need to associate any form of meta data to an already existing object, this would definitely be a good way of doing so.

Another interesting note is that the object key is a reference to the object. If you have another variable referencing an already existing key object, the JavaScript engine will treat this key as a duplicate.

let map = new Map();
let obj1 = {};
let obj2 = {};


let obj3 = obj1;	// reference


map.set(obj1, "Val1");
map.set(obj2, "Val2");


map.set(obj3, "Val3");	// duplicate to obj1 key

console.log(map.get(obj1));

Map() methods

Maps include the following 3 methods which are also found when working with Sets(). This makes incorporating either data structures into your code a more fluid experience as you don't have to remember different sets of methods for each.

- has(key) => determines whether a map includes a specific key
- delete(key) => removes the key/value from the map
- clear() => removes all key/values from a given map

The size property

Maps also include the size property that will return the number of key/value pairs in a given map.

let map = new Map();

map.set("key1", "val1");
map.set("key2", "val2");


console.log(map.size);		// 2

Initialize with an array

Maps share this feature with Sets, in that they can be initialized by passing in an Array as a given argument. Because Maps require both a key and a value however, the array passed in must itself be an array of arrays (2D array). And that will look something like the following:

let array = new Array();


array.push(["key1", "value1"]);
array.push(["key2", "value2"]);


let map = new Map(array);

This will create a new Map with the given keys of "key1" and "key2". This method works mainly because keys in a Map can be of any given data type. This makes Arrays the perfect data structure for storing this type of data, since Arrays can store any type of data and do not coerce values to strings.

The forEach() method

Maps also support use of the forEach() method for item traversal.

The forEach method takes in 1 argument, which will be a callback function with 3 parameters. Note that it is slightly different from the array version, in that the second argument is the corresponding key and not an index. The 3 parameters are defined as follows: 

1. The value from the next position in the Map
2. The key for that value
3. The Map from which the value is read

let map = new Map();

map.set("key1", "val1");
map.set("key2", "val2");


map.forEach(function(value, key, ownermap){

});

The forEach for Maps will iterate through the items in the order that they were added to the Map initially.

And that's it for this lesson on ES6 Maps. Sets and Maps are a great addition to the language and makes working with datasets a much simpler process that in the past required a more clever use of Arrays and objects.

Keep an eye out for future ES6 and ES.Next posts where we will dive deeper in the quickly growing specification list of JavaScript.

Walter Guevara is a software engineer, startup founder and currently teaches programming for a coding bootcamp. He is currently building things that don't yet exist.

Comments

No messages posted yet

Developer Poll

Q:

Stay up to date

Sign up for my FREE newsletter. Get informed of the latest happenings in the programming world.

Add a comment

Keep me up to date on the latest programming news
Add Comment

Stay up to date

Get informed of the latest happenings in the programming world.

No thanks