Menü schliessen
Created: September 20th 2024
Last updated: November 12th 2024
Categories: Common Web Development,  IT Development,  JavaScript Development
Author: Tim Fürer

JavaScript: How to use Map; The Super-Powered Object/Dictionary

Tags:  guide,  Javascript
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

JavaScript's dictionaries, generally referred to as objects, are basic and limited. Entries can strictly only be keyed by strings and doing certain interactions with them (such as iterating over all entries) requires the assistance of static methods that live on the Object class, which is hardly elegant.


The Solution: Maps

Introduced with the 6th edition of JavaScript in 2015, Maps are essentially super-powered objects. Map entries' keys can be anything from primitives (that's things such as booleans, numbers, and strings), objects, and even functions. Interactions conveniently live as methods on the individual Map instances, making them accessible in an easy and consistent manner.

Let's compare Maps and Objects over some basic interactions that are possible with both. This will help us get comfortable with Maps and teach us how to transition to them from Objects.

Declaration

Object

const object = {};
const object = {
    '1': 1,
    '2': 2,
    '3': 3,
};

Map

const map = new Map();
const map = new Map([
    ['1', 1],
    ['2', 2],
    ['3', 3],
]);

Setting Values

Object

object['foo'] = 'bar';

Map

map.set('foo', 'bar');

Getting Values

Object

object['foo']

Map

map.get('foo')

Checking for a Key's Existence

Object

'foo' in object

Map

map.has('foo')

Removing a Key

Object

delete object['foo'];

Map

map.delete('foo');

Looping over Entries

Object

for (const [key, value] of Object.entries(object)) {
    //
}

Map

for (const [key, value] of map.entries()) {
    //
}
map.forEach((value, key) => {
    //
});

Getting Keys

Object

for (const key of Object.keys(object)) {
    //
}
Object.keys(object)

Map

for (const key of map.keys()) {
    //
}
Array.from(map.keys())