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 add() 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.

If you are interested in learning more, check out our guide on sets in JavaScript.

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

πŸ™Œ Join the weekly newsletter and get the latest tutorials from my blog and around the internet.
No spam, ever. You can unsubscribe anytime.

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.