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


Borislav Hadzhiev

Fri Oct 29 20211 min read


Photo by Adam Wilson

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.

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, which allows you to chain multiple calls to the set() method.

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

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 #

Use the search field on my Home Page to filter through my more than 1,000 articles.