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

pagemap, a mini map navigation for web pages

Many text editors nowadays sport a minimap on the right hand side of the screen. Pagemap is like that, but for webpages:

To use it, position a canvas element fixed on your screen, and tell pagemap which elements to include in the map:

<canvas id="map"></canvas>
#map {
    position: fixed;
    top: 0;
    right: 0;
    width: 200px;
    height: 100%;
    z-index: 100;
}
pagemap(document.querySelector('#map'), {
    viewport: null,
    styles: {
        'header,footer,section,article': rgba(0,0,0,0.08),
        'h1,a': rgba(0,0,0,0.10),
        'h2,h3,h4': rgba(0,0,0,0.08)
    },
    back: rgba(0,0,0,0.02),
    view: rgba(0,0,0,0.05),
    drag: rgba(0,0,0,0.10),
    interval: null
});

Installation per npm/yarn

$ yarn add pagemap

pagemap – minimap for web pages →
pagemap source (GitHub) →