# Add an element to a Map in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Dec 4, 2022, updated Jun 7, 2023. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-map-add-element

> Learn how to use the set() method to add elements to a Map in JavaScript.

You can use the `set()` method to dynamically add elements to a `Map` object in JavaScript. The `set()` method adds or updates an element with the given key and value, and it returns the `Map` object itself.

```javascript
const map = new Map()

map.set('name', 'John Doe')
map.set('age', 27)
map.set('country', 'Pakistan')

console.log(map)

// Map(3) {
//   'name' => 'John Doe',
//   'age' => 27,
//   'country' => 'Pakistan'
// }
```

Since the `set()` method returns the same `Map` object, you can chain multiple `set()` calls together to add multiple elements:

```javascript
const map = new Map()

map.set('name', 'John Doe').set('age', 27).set('country', 'Pakistan')

console.log(map)

// Map(3) {
//   'name' => 'John Doe',
//   'age' => 27,
//   'country' => 'Pakistan'
// }
```

It's important to note that `Map` keys are unique. If you call the `set()` method multiple times with the same key, it will update the value associated with that key:

```javascript
const map = new Map()

map.set('name', 'John')
map.set('name', 'John Doe')

console.log(map)

// Map(1) {
//   'name' => 'John Doe'
// }
```

In the above example, the value for the key `'name'` is initially set to `'John'`, but it is then updated to `'John Doe'` in the second `set()` call.

The `Map` object allows you to store various types of objects as keys or values, including object literals, arrays, and functions:

```javascript
const menu = {
  sandwich: '?',
  cookie: '?',
  popcorn: '?'
}

const pizza = () => '?'

const foods = new Map()

foods.set(menu, 5.9)
foods.set(pizza, 'What is Pizza?')

console.log(foods.get(menu)) // 5.9
console.log(foods.get(pizza)) // What is Pizza?
```

In the above example, an object literal (`menu`) and a function (`pizza`) are used as keys in the `Map` object, and their corresponding values are retrieved using the `get()` method.

To learn more about the `Map` object and how to use it to create collections of key-value pairs in JavaScript, you can refer to [this article](https://attacomsian.com/blog/maps-javascript).
