JavaScript ES6: Map objects

Introduction

The 6th edition of ECMAScript, the official name of the JavaScript programming language, was finalized in 2015. This update adds significant new syntax for writing complex applications, including class declarations, let and const keywords, Map and Set objects, promises, template literals, iterators, generators, and arrow functions. The complete list of new features is extensive.

In this blog post, we’re going to focus on Map objects.

Click to enlarge

Map objects

The Map object stores (key, value) pairs, remembering the original insertion order of the keys. You can use any value, both primitive types and objects as keys. For example, in the sample code below, we query a database for a list of states (e.g. “New York”), build a map of those states, and then log all states that start with the letter “N”.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function getStateMap() {

    //  stateRows is an array of objects, each of which is of the form { "abbrev": "NY", "name": "New York" }
    const stateRows = queryDatabaseForStates();

    const stateMap = new Map();
    stateRows.forEach( ( stateRow ) => {
        stateMap.set( stateRow.abbrev, stateRow.name );
    } );

    return stateMap;
}

function logStatesStartingWithN() {

    const stateMap = getStateMap();

    for ( const [ abbrev, name ] of stateMap ) {
        if ( abbrev.startsWith( "N" ) ) {
            console.log( abbrev + " - " + name );
        }
    }
}

Let’s break down this code:

  • Line 1 - We define a function that will return a map of all states

  • Line 4 - We query a database for the list of states

  • Line 6 - We construct a new, empty map

  • Line 7 - We iterate through the rows returned by the database

  • Line 8 - We add each state to the map, using the state’s abbreviation (e.g. “NY”) as the key and its name (e.g. “New York”) as the value

  • Line 11 - We return the populated map

  • Line 14 - We define a function that will log all states starting with the letter “N”

  • Line 16 - We retrieve a map of all states

  • Line 18 - We iterate through the map using a for…of statement

  • Line 19 - If the abbreviation starts with an “N”…

  • Line 20 - We log the abbreviation and name to the console

Properties and methods

A Map object has a single instance property:

  • size - Returns the number of (key, value) pairs in the map

and a variety of instance methods:

  • clear() - Removes all (key, value) pairs from the map

  • delete( key ) - Removes the (key, value) pair with the given key from the map

  • get( key ) - Return the value associated with the key

  • has( key ) - Return a boolean indicating whether the given key is in the map

  • set( key, value ) - Sets the value for the given key in the map

  • keys() - Returns a new Iterator object that contains the keys in the map, in insertion order

  • values() - Returns a new Iterator object that contains the values in the map, in insertion order

  • entries() - Returns a new Iterator object that contains an array of [key, value] arrays in the map, in insertion order

  • forEach( callback ) - Calls the callback function once for each (key, value) pair in the map, in insertion order, passing three arguments to the callback:

    • value

    • key

    • map

Maps vs. objects

An object is similar to a map. Both let you:

  • Define (key, value) pairs

  • Retrieve the value for a key

  • Determine whether a key exists

  • Delete keys

For this reason, an object has been used as a map historically. But, there are important differences between objects and maps that make maps preferable in certain cases. They are:

Topic

Unexpected keys

Map

A map does not contain any keys by default

Object

An object has a prototype, so it contains default keys that could interfere with your own keys


Key types

Keys can be of any type, including primitive types and objects

Keys must be strings or symbols


Key order

Iteration of the map returns items in the order that they were inserted

Items are not guaranteed to be returned in the order that they were inserted


Size

The number of items in the map is returned by the size property

The number of items in the object must be calculated manually


Iteration

A map is an iterable; it can be directly iterated

An object is not an iterable; it cannot be directly iterated. One can retrieve an iterable for an object using Object.keys() or Object.entries().


Performance

If you are performing frequent additions to and removals from the map, a map will perform better than an object

Not optimized for frequent additions to and removals from the map


Serialization

There is no native serialization of a map to JSON, nor parsing of JSON into a map. But, workarounds do exist.

Native support for serialization of an object to JSON and parsing of JSON to an object


Support

Maps are supported by all major browsers, with the exception of Internet Explorer, and Node.js.

Source: https://www.finitewisdom.com/people/joshua...