Add an element to a Map in JavaScript

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

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 back the same Map object, you can chain multiple calls together, as shown below:

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'
// }

The Map keys are unique. It means calling the set() method more than once with the same key won't add multiple key-value pairs. Instead, the value is replaced with the newest value:

const map = new Map()

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

console.log(map)

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

The Map object allows us to store object literals, arrays, and even functions as a key or value:

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?

Read this article to learn more about the Map object and how to use it to create collections of key-value pairs in JavaScript.

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

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.