Friday, September 5, 2025
HomeLanguagesJavascriptJavaScript Program to Update the Value for a Specific Key in Map

JavaScript Program to Update the Value for a Specific Key in Map

In this article, we will see different approaches to update the value for a specific key in Map in JavaScript. JavaScript Map is a collection of key-value pairs. We have different methods to access a specific key in JavaScript Map.

Methods to update the value for a specific key in Map in JavaScript

  • Using the JavaScript Map set() Method
  • Using Map.forEach() Method

Method 1: Using JavaScript Map.set() method

In this method, we will use the built-in Map.set() method to update the value for a specific key.

Example: In this example. we will update the value of key(‘b’) in the given map using the map.set() method.

Javascript




let m = new Map([
      ["a", 100],
      ["b", 200],
]);
  
console.log("Old value for key: 'b', "+m.get('b'));
m.set('b',1000)
console.log("New value for key: 'b', "+m.get('b'));


Output

Old value for key: 'b', 200
New value for key: 'b', 1000

Method 2: Using Map.forEach() method

In this method, we will iterate the map using map.forEach() method to iterate the key-value pairs and update the value for specific key.

Example: In this example, we will iterate map using forEach method and update the value for a specific key using if condition.

Javascript




// Creating a map object
let m = new Map([
    ["a", 100],
    ["b", 200],
]);
  
// Display old value
console.log("Old value for key: 'b', " + m.get("b"));
  
  
// Iterate and change the required value 
m.forEach((value, key) => {
    if (key == "b") m.set(key, 1000);
});
  
// Display updated value
console.log("New value for key: 'b', " + m.get("b"));


Output

Old value for key: 'b', 200
New value for key: 'b', 1000
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6637 POSTS0 COMMENTS
Nicole Veronica
11802 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11865 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7027 POSTS0 COMMENTS
Thapelo Manthata
6704 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS