Javascript. Maps and Weak Maps

The Javascript Map object was added to solve some of the limitations that Javascript had. Discover all its features!

The Map object

const map = new Map();
const initialValues = [["key1", "value1"], ["key2", "value2"]];
const map = new Map(initialValues);
const map = new Map([['foo', 1], ['bar', 2]]);
console.log(map.keys()); // MapIterator {"foo", "bar"}
map.forEach((key, value) => { /* do something */ });
for ([key, value] of map2) { 
console.log(`${key} ${value}`);

Differences with flat Javascript objects

const a = {};
const b = {[a]: 'foo'};
console.log(b); // {[object Object]: "foo"}
const a = {};
const b = true;
const fn = () => {};
const map = new Map();
map.set(a, 'foo');
map.set(b, 'bar');
map.set(fn, 'zeta');
console.log(map.get(a)); // 'foo'
console.log(map.get(b)); // 'bar'
console.log(map.get(fn)); // 'zeta'
const map = new Map([['foo', 1], ['bar', 2]]);
console.log(map.size); // 2

The WeakMap Object

♻️ Garbage collector?

WeakMaps Features

const a = {};
const weakMap = new WeakMap();
weakMap.set(a, 'foo');
// if we loose a, we loose the abject to 'foo'

Uses of WeakMaps

const person = {name: 'Gerardo'};
const weakMap = new WeakMap();
weakMap.set(person, 'some interesting property of person';
function calculateShipping(item) {
/* some expensive operations */
const itemInCart = {...};
const map = new WeakMap();
map.set(itemInCart, calculateShipping(itemInCart));

Final thoughts

Written by

Entre paseo y paseo con Simba desarrollo en Symfony y React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store