Maps in JavaScript
Tags: javascript, webdev, beginners, codenewbie
Published: 2019-06-19 11:14:51


*This post was originally published on [attacomsian.com/blog](https://attacomsian.com/blog/maps-javascript).*

---

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](https://dev.to/attacomsian/sets-in-javascript-2hk7) 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:

```javascript
const items = new Map(); 
```

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

```javascript
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:

```javascript
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:

```javascript
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:

```javascript
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:

```javascript
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:

```javascript
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:

```javascript
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:

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

Similar to [sets](https://attacomsian.com/blog/maps-javascript#keys-and-values), you can call the `next()` method on the iterable returned by the `entries()` method to traverse the key-value pairs one-by-one:

```javascript
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**](https://attacomsian.com/newsletter) to get web development tutorials & protips every week.

---

**Like this article?** [Follow @attacomsian on Twitter](https://twitter.com/attacomsian). You can also follow me on [LinkedIn](https://linkedin.com/in/attacomsian) and [DEV](https://dev.to/attacomsian).