Introduction to JavaScript Classes: Maps

Introduction to JavaScript Classes: Maps

Until recently, the major data structures we used in JavaScript were Objects and Arrays. Maps and Sets were introduced with ES6 (also called ES2015). This article introduces Maps, its differences compared to a pre-existing JavaScript data structure, and how Maps works.

What is a Map?

Maps are a collection of keyed data items, just like Objects. But the main difference is that Map allows keys of any type. The key could be a string, boolean, array, or even a DOM element.

const rachelMap = new Map();

rachelMap.set('name', 'rachel');
rachelMap.set('age', 20);
rachelMap.set(true, 1);
rachelMap.set(false, 0);
rachelMap.set(aDOMElement, someData)

console.log(rachelMap);
//{ 'name' => 'rachel', 'age' => '20', true => 1, false => 0, aDOMElement => somData }

Objects are similar to Maps, both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. For this reason (and because there were no built-in alternatives), Object has been used as Map historically.

Differences Between Map and Object

  • The keys of an Object are Strings and Symbols, where they can be any value for a Map.
  • You can get the size of a Map easily while you have to manually keep track of size for an Object.
  • A Map iterates its elements in insertion order, whereas iteration order is not specified for Objects.
  • A substantial disadvantage for Maps is that they are not supported with JSON directly. Objects are easily stringified and parsed, unlike Maps.

From this tweet by Minko Gechev shows the major differences.

Methods and Properties of a Map

How to create a Map

We can create an empty map and add values to it, or we can create it with some initial values.

// creating a map with some initial values
const testScores = new Map([
    ['Rachel', 12],
    ['Banky', 11],
    ['Dave', 15],
    ['Didi', 14]
]);

// creating an empty map
const examScores = new Map();

How to add and remove data from a Map

const examScores = new Map();

// to add new data a key-value pair, you call the Map set method
// pass in the key and it's value
examScores.set('Rachel', 64);
examScores.set('Dave', 60);

//the Map set method is also chainable
examScores.set('Rachel', 64).set('Dave', 60);


// to remove a key-value pair, you only need to call the Map delete method.
// using the key as the argument
examScores.delete('Rachel');

Get Value from Map

const daveExamScore = examScores.get('Dave');
console.log(daveExamScore); // 60

//If you pass a key that is not in the map, the get() method will return undefined.

const rachelExamScore = examScores.get('Rebecca');
console.log(rachelExamScore); // undefined

Check the existence of an element by key

examScores.has('Dave'); // true
examScores.has('lily'); // false

Get the number of elements in the Map

The size property of Map returns the number of data entries in the Map.

console.log(testScores.size); // 4

Iterate over Map keys and values

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

//'Rachel', 12
//'Banky', 11
//'Dave', 15
//'Didi', 14

When to use Maps instead of plain JavaScript objects

The plain JavaScript Object { key: 'value' } holds structured data. But a plain JavaScript object has its limitations.

  • Use maps over objects when keys are unknown until runtime because keys formed by user input or unknowingly can break the code which uses the object if those keys overwrite the inherited properties of the object, so maps are safer in those cases.
  • Use maps if there is a need to store primitive values as keys.
  • Use objects if we need to operate on individual elements.

Conclusion

A Map will make it easy to create and update the values and also to look up the values based on a key. It’s hard to believe that we can seriously program without maps.

Besides the advantage of Maps preserving key types as well as being able to support things like objects as keys, they are isolated from the side effects that objects much have. A Map is a pure hash, there's no confusion about trying to be an object at the same time.