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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee