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

Tomasz Zwierzchoń
Nov 27, 2017 · 2 min read

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

Orba

We create and develop B2B & B2C e-commerce systems

Tomasz Zwierzchoń

Written by

IT Architect. FrontEnd Team Lead. #JavaScript on #IoT #UX #Vue.js Fan. I miss having free time, especially for dancing Tango.

Orba

We create and develop B2B & B2C e-commerce systems