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.

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:

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:

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:

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.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.