Member-only story

JavaScript Maps and how to use them

Kristijan
4 min readOct 19, 2020

--

A few days back, a colleague of mine shared this post about JavaScript maps and the benefits of their usage. The map is a newer feature of JavaScript. It is only available since ES6. So no wonder it is not as popular feature as it probably should be. Then again, just using an ordinary object might seem more comfortable to use than a map. That is the reason for this post. I am not covering why you should use maps. But it is a cheat sheet on how to use them.

Basics

If you want to replace JavaScript objects with maps, you want them to support the same primary functions. And they do, just slightly different. The following examples demonstrate how to create a map, insert an item, get it, and remove it from the map.

Creating map

A map is an object; therefore, you need to use a new keyword to create it.

const map = new Map();

Using map

Once you create it, you can use a list of different functions that it provides.

// insert into map
map.set("key", "value");
// get value from map
map.get("key"); //value
// get value for non-existing key
map.get("non-existing-key"); // undefined
// remove item from map
map.delete("key"); // true

--

--

No responses yet