How to add a Key/Value pair to a Map in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Add a Key/Value pair to a Map #

Use the set() method to add a key/value pair to a Map, e.g. map.set('myKey', 'myValue'). The set() method adds or updates the element with the provided key and value and returns the Map object.

index.js
const map1 = new Map(); map1.set('country', 'Chile'); map1.set('age', 30); // 👇️️ {'country' => 'Chile', 'age' => 30} console.log(map1); console.log(map1.get('country')); // 👉️ Chile // ✅ With chaining map1.set('number', 5) .set('color', 'blue') .set('city', 'Santiago');

We used the Map.set() method to add key/value pairs to a Map.

The method takes 2 parameters:

  1. the key of the element
  2. the value of the element
The set() method returns the Map object. This allows us to chain multiple calls to the set() method.

Note that the keys and values of a Map can be of any type, e.g. an object.

index.js
const map1 = new Map(); const obj = {country: 'Chile'}; map1.set(obj, {city: 'Santiago'}); // 👇️ { {country: 'Chile'} => {city: 'Santiago'} } console.log(map1); console.log(map1.get(obj)); // 👉️ {city: 'Santiago'}

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.