Thursday, September 4, 2025
HomeLanguagesJavascriptJavaScript Map set() Method

JavaScript Map set() Method

The map.set() method is used to add key-value pairs to a Map object. It can also be used to update the value of an existing key. Each value must have a unique key so that they get mapped correctly.

Syntax:

GFGmap.set(key, value);

Parameters: This method accepts two parameters as mentioned above and described below:

  • Key: This is the key of the item that has to be added or updated in the Map.
  • Value: This is the value of the item that has to be added or updated in the Map.

The examples below illustrate the set() method:

Example 1:

Javascript




<script>
  let GFGMap = new Map();
  
  // Adding a key value pair
  GFGMap.set(1, "India");
  
  // Getting the value by key
  console.log(GFGMap.get(1));
  
  // Updating the existing value
  GFGMap.set(1, "England");
  
  // Getting the value back
  console.log(GFGMap.get(1));
</script>


Output :

India
England

Example 2: Using set() with chaining

Javascript




<script>
  let myMap = new Map();
  
  // Adding key value pair with chaining
  myMap.set(1, "Rohan").set(2, "Sohan").set(3, "Trojan");
  
  // Getting the values back
  console.log(myMap.get(1));
  console.log(myMap.get(2));
  console.log(myMap.get(3));
</script>


Output :

Rohan
Sohan
Trojan
RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS