Stop Using Objects as Hash Maps in JavaScript

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

About the Author

Bramus is a Freelance Web Developer from Belgium. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.