DEV Community

Atta
Atta

Posted on • Edited on • Originally published at attacomsian.com

Maps in JavaScript

This post was originally published on attacomsian.com/blog.


Maps are a new data structure in JavaScript that allows you to create collections of key-value pairs. They were introduced with ES6 (also called ES2015) along with sets in JavaScript. A map object can store both objects and primitives as keys and values.

Maps are similar to objects which are also used for storing key-value data. But the main difference is that map keys can be of any type and are not limited to just strings and symbols. Unlike objects, it is also easier to get the size of the map.

Initialize a Map

Just like sets, you can use Map() constructor to create an empty map:

const items = new Map(); 

You can also pass an iterable (such as array) to the constructor to initialize the map:

const items = new Map([['🦅', 'Eagle'], ['🐶', 'Dog']]); 

Map Methods

The main methods and properties are set(), get(), has(), size, delete(), and clear(). Here is a simple example of a map showing the use of these methods:

const items = new Map();

// add items
items.set('🐶', 'Dog');
items.set('🦅', 'Eagle');
items.set('🚄', 'Train');
items.set(45, 'Number');
items.set(true, 'Boolean');

// get item
items.get(45); // Number
items.get('🐶'); // Dog
items.get('🐺'); // undefined

// check if key exists
items.has('🚄'); // true
items.has('🐺'); // false

// get items count
items.size; // 5

// delete item
items.delete('🦅'); // true
items.delete('🦅'); // false - already removed

// delete all items
items.clear();

Like sets, map keys are also unique. Calling set() more than once with the same key won't add multiple key-value pairs. Instead, the value part is replaced with the newest value:

const animals = new Map();

animals.set('🐺', 'Wolf');
animals.set('🐺', 'Wolf Face');

console.log(animals); // Map(1) {"🐺" => "Wolf Face"}

Objects in Map

Since maps allow us to store any data type as key or value, we can store complex objects like object literals, arrays and even functions:

const props = {
    browser: 'Chrome',
    os: 'Ubuntu 19.04'
};

const hamburger = () => '🍔'; 

const things = new Map();

things.set('birds', ['🦉', '🦅']);
things.set('user', {name: 'John Doe', planet: 'Earth'});
things.set(props, 59);
things.set(hamburger, 'What is the food?');

things.get(props); // 59
things.get(hamburger); // What is the food?

Iterating over Maps

Unlike objects, when we iterate over the map, the key-value pairs are returned in the same order as they were inserted. We can use for...of loop to iterate over all key-value pairs:

const foods = new Map([
    ['🍌', 'Banana'],
    ['🍕', 'Pizza'],
    ['🥒', 'Cucumber'],
    ['🌽', 'Maize'],
]);

for (const [key, value] of foods) {
    console.log(`${key}: ${value}`);
}

// 🍌: Banana
// 🍕: Pizza
// 🥒: Cucumber
// 🌽: Maize

Similarly, we can also use the built-in forEach() method to iterate over all elements:

foods.forEach((key, value) => {
    console.log(`${key}: ${value}`);
});

Keys and Values

Maps provide keys() and values() methods to access the keys and values only. These methods return a new iterable object which can also be used to iterate over all keys or values:

for (const key of foods.keys()) {
    console.log(key);
}

for (const value of foods.values()) {
    console.log(value);
}

The Map object also have entries() method that returns an iterable for entries [key, value]. This method is used by default in for...of loop. Here's an example:

for (const [key, value] of foods.entries()) {
    console.log(`${key}: ${value}`);
}

Similar to sets, you can call the next() method on the iterable returned by the entries() method to traverse the key-value pairs one-by-one:

const entries = foods.entries();

console.log(entries.next()); // {value: ["🍌", "Banana"], done: false}

Conclusion

A map is a collection of key-value pairs, which allows us to store both objects and primitives as keys and values. Unlike objects, map keys can be of any type: objects, arrays, functions or even another map. Similar to sets, the keys are unique; they can only occur once in the map. When we iterate over a map object, the key-value pairs are returned in the same order they were inserted in the map.


✌️ I write about modern JavaScript, Node.js, Spring Boot, and all things web development. Subscribe to my newsletter to get web development tutorials & protips every week.


Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV.

Top comments (10)

Collapse
 
georgecoldham profile image
George

This is a great overview! I was expecting it to be the other map as that seems to be what people focus on and use more. But I am pleasantly surprised that you are highlighting less used but very useful functionality.

Why people dont use these more is a mystery to me. I often see people using Objects or even JSON without ever stopping to think about Map

Collapse
 
attacomsian profile image
Atta

May be because Maps are relatively new (introduced in ES6) whereas Objects are around since JavaScript version 1 and supported by all browsers.

Collapse
 
laurieontech profile image
Laurie

Same though!

Collapse
 
emnudge profile image
EmNudge

You wrote

Calling add() more than once with the same key won't add multiple key-value pairs.

I believe you may have meant set()

Collapse
 
attacomsian profile image
Atta

Yeah, it should be set() method for maps :) I updated the post.

Collapse
 
calag4n profile image
calag4n

Wow, I didn't know that, thanks !
I don't see use cases for now but it seems pretty cool .

Collapse
 
dharmelolar profile image
Dharmelolar Ezekiel

Thank you so much for this post. I've been stucked on map for awhile now and i have been using references online but this is the only one i've found useful so far.

Collapse
 
attacomsian profile image
Atta

Thank you! I'm glad it helped ✌️

Collapse
 
mgecmez profile image
mgecmez

Hi Atta,

Thank you so much for this post.

I have a question. How to post typescript map object to .net core webapi?

Collapse
 
sirluis profile image
Luis Henrique

Actually Map.prototype.forEach does not behave like his array cousin. It returns a iterator.