# Introduction to Map object in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published May 17, 2019, updated Jun 7, 2023. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/maps-javascript

> A quick introduction to ES6's newest data type Map and how to a collection of key-value pairs in JavaScript.

The `Map` object in JavaScript allows us to create collections of key-value pairs. Keys in a `Map` are unique and maintain their original insertion order. You can use any objects or primitives as keys and values.

## Objects vs. Maps

Introduced in ES6 alongside the [`Set`](https://attacomsian.com/blog/sets-javascript) object, the `Map` object is similar to a [JavaScript object](https://attacomsian.com/blog/objects-prototypes-classes-javascript#objects) used for storing key-value data. However, there are important distinctions:

1. `Map` keys can be of any type, not limited to strings and symbols.
2. A `Map` object provides a property to retrieve the size of the collection.
3. By default, a `Map` does not contain any keys it only includes explicitly inserted entries.

## Creating a new Map object

To create an empty map, use the `Map()` constructor:

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

Alternatively, you can initialize a map with values by passing an iterable object like an array to the `Map` constructor:

```javascript
const items = new Map([
  ['?', 'Eagle'],
  ['?', 'Dog'],
  ['?', 'Hamster']
])

console.log(items)
// Map(3) { '?' => 'Eagle', '?' => 'Dog', '?' => 'Hamster' }
```

Another approach is to initialize a map with values from a JavaScript object:

```javascript
const user = { name: 'John Doe', age: 30 }

const map = new Map(Object.entries(user))
console.log(map)

// Map(2) {
//     'name' => 'John Doe',
//     'age' => 30
// }
```

## Adding elements to a Map

The `set()` method is used to add elements to a `Map` object:

```javascript
const items = new Map()
items.set('?', 'Dog')
items.set('?', 'Eagle')
items.set('?', 'Train')
items.set(45, 'Number')
items.set(true, 'Boolean')
```

The `set()` method is chainable, allowing you to combine multiple `set()` calls:

```javascript
const user = new Map()

user.set('name', 'Atta').set('age', 34)

console.log(user)
// Map(2) { 'name' => 'Atta', 'age' => 34 }
```

Since `Map` keys are unique, calling `set()` with the same key multiple times will update the value instead of creating multiple key-value pairs:

```javascript
const animals = new Map()

animals.set('?', 'Wolf')
animals.set('?', 'Wolf Face')

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

## Adding objects to a Map

Since the `Map` object allows storing any data type as keys or values, you can include 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?
```

## Getting an element from a Map

To retrieve elements from a `Map` object, use the `get()` method:

```javascript
const user = { name: 'Atta', age: 30 }

const items = new Map()
items.set('user', user)
items.set('rank', 12)

console.log(items.get('rank')) // 12
console.log(items.get('user')) // { name: 'Atta', age: 30 }
```

## Checking if an element exists in a Map

To determine if an element exists in a `Map` object, use the `has()` method:

```javascript
const items = new Map()
items.set('?', 'Dog')
items.set('?', 'Eagle')

console.log(items.has('?')) // true
console.log(items.has('?')) // false
```

## Getting the number of elements in a Map

The `Map` object provides the `size` property to retrieve the number of elements in the collection:

```javascript
const items = new Map()
items.set('?', 'Dog')
items.set('?', 'Eagle')

console.log(items.size) // 2
```

## Deleting an element from a Map

To remove an element from a `Map` object, use the `delete()` method:

```javascript
const items = new Map()
items.set('?', 'Dog')
items.set('?', 'Eagle')

console.log(items.delete('?')) // true
console.log(items.delete('?')) // false (already removed)
console.log(items.delete('?')) // false (not found)
```

## Deleting all elements in a Map

To delete all entries in a `Map` object, use the `clear()` method:

```javascript
const items = new Map()
items.set('?', 'Dog')
items.set('?', 'Eagle')

items.clear()

console.log(items.size) // 0
```

## Iterating over Map keys

The `keys()` method returns an iterator object containing all the keys in a `Map` object. You can use it with a [`for...of`](https://attacomsian.com/blog/javascript-for-of-loop) loop to iterate over the keys:

```javascript
let john = { name: 'John Doe' },
  alex = { name: 'Alex' },
  pretti = { name: 'Pretti' }

const team = new Map([
  [john, 'Manager'],
  [alex, 'Lead'],
  [pretti, 'Developer']
])

for (const user of team.keys()) {
  console.log(user)
}

// { name: 'John Doe' }
// { name: 'Alex' }
// { name: 'Pretti' }
```

## Iterating over Map values

To iterate over the values in a `Map` object, use the `values()` method:

```javascript
let john = { name: 'John Doe' },
  alex = { name: 'Alex' },
  pretti = { name: 'Pretti' }

const team = new Map([
  [john, 'Manager'],
  [alex, 'Lead'],
  [pretti, 'Developer']
])

for (const role of team.values()) {
  console.log(role)
}

// Manager
// Lead
// Developer
```

## Iterating over Map elements

You can use a `for...of` loop to iterate over all key-value pairs in a `Map` object. The order of iteration follows the original insertion order of the keys:

```javascript
const foods = new Map([
  ['?', 'Banana

'],
  ['?', 'Pizza'],
  ['?', 'Cucumber'],
  ['?', 'Maize']
])

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

// ?: Banana
// ?: Pizza
// ?: Cucumber
// ?: Maize
```

Alternatively, you can use the [`forEach()`](https://attacomsian.com/blog/javascript-foreach) method to iterate over all elements:

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

// ?: Banana
// ?: Pizza
// ?: Cucumber
// ?: Maize
```

The `Map` object also provides the `entries()` method, which returns an iterable for key-value pairs `[key, value]`:

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

You can call the `next()` method on the iterable returned by `entries()` to traverse the key-value pairs one by one:

```javascript
const entries = foods.entries()

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

## Converting a Map to an array

To convert a `Map` object to a two-dimensional array, you can use the `Array.from()` method:

```javascript
const foods = new Map([
  ['?', 'Banana'],
  ['?', 'Pizza'],
  ['?', 'Cucumber'],
  ['?', 'Maize']
])

const arr = Array.from(foods)
console.log(arr)

// [
//   ['?', 'Banana'],
//   ['?', 'Pizza'],
//   ['?', 'Cucumber'],
//   ['?', 'Maize']
// ]
```

Alternatively, you can use the spread operator (`...`) to convert a `Map` object to an array:

```javascript
const arr = [...foods]
console.log(arr)

// [
//   ['?', 'Banana'],
//   ['?', 'Pizza'],
//   ['?', 'Cucumber'],
//   ['?', 'Maize']
// ]
```
