Photo by Steve Johnson on Unsplash
A map is one of the most frequently used data structures in daily programming. It keeps key-value pairs that can easily be accessed by their keys.
In JavaScript, it is quite convenient to just use a plain object for that purpose. But there is a built-in data structure in JavaScript that was made for exactly that purpose:
Map
.
// Don't
const plainObjMap = {};
plainObjMap['someKey1'] = 1;
plainObjMap['someKey2'] = 2;
plainObjMap['someKey3'] = 3;
// Do
const map = new Map();
map.set('someKey1', 1);
map.set('someKey2', 2);
map.set('someKey3', 3);
Note that this isn’t a case against using a map but against “using an Object
as a map”, as using the Map
type comes with a few advantages such as guaranteed key order and being more performant.
Stop Using Objects as Hash Maps in JavaScript →
MDN: Map: Objects vs. Maps