How to use Map.has() and Map.set() Methods In Javascript
In this method, we will first check if the Map contains the specific key using the has() method. If the key is present, we will then use the set() method to update its value.
Example:
// 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"));
// Check if the key exists and update the value
if (m.has("b")) {
m.set("b", 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
In this example, we will update the value of key (‘b’) in the given map only if it exists, using the has() and set() methods.
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.