Forward Thinking — a never-complete guide to modern JavaScript #5 Maps

Tomasz Zwierzchoń
Orba
Published in
2 min readNov 27, 2017

In the part #3 of my guide we were discovering Sets. Now it’s time for maps.

Maps are ordered lists of key-value pairs. The key and the value can have any type. This is the main difference between objects keys and maps.

Try this code:

const log = x => console.log(x);
const objectMap = Object.create(null);
objectMap[123] = 'abc';
log(objectMap['123']);
log(objectMap[123]);
const map = new Map();
map.set(123, 'abc');
map.set('123', 'cba');
log(map.get(123));
log(map.get('123'));

We can even use objects as a keys:

const log = x => console.log(x);
const object1 = {};
const map = new Map();
map.set(object1, 'some value');
log(map.get(object1));

We can use it to store addtional data in objects without a need of a jQuery data method:

const log = x => console.log(x);
const el = document.querySelector('html');
const map = new Map();
map.set(el, 'some value');
log(map.get(el));

This approach has one problem. When we delete a node from DOM it is still present in the map. But we can fix it easily. Weak maps to the help!

In weak maps every key must be an object and when key reference outside map is deleted, the key-value pair is removed from it.

Try this code:

const log = x => console.log(x);
const query = x => document.querySelector(x);
const body = query('body');
const map = new WeakMap();
body.innerHTML = '<div id="div1"></div><div id="div2"></div>';let el = query('#div1');
map.set(el, 'some value');
log(`Before delete: ${map.get(el)}`);
el = null;
log(`After delete: ${map.get(el)}`);

More about Maps here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

--

--

Tomasz Zwierzchoń
Orba
Editor for

Skilled team leader and trainer. I excel at translating between business and technical languages. I am well-versed in agile methodologies, BDD, and TDD.