1console.log("hello-world);console.log("hello-world);.container {
  width: 80%;
}<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>1console.log("hello-world);console.log("hello-world);.container {
  width: 80%;
}<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>In this blog you will understand how to efficiently add key/value pairs to a Javascript Map, common errors, and a fun coding problem to polish your skills.
Before diving into the methods, let’s briefly recap what Maps are in JavaScript. Maps are collections that store key-value pairs. They stand out for following:
size property.The set() method is your primary tool for inserting or modifying key-value pairs in a Map.
const map1 = new Map();
map1.set('username', 'alexdoe');
map1.set('age', 25);
console.log(map1); // Map(2) {'username' => 'alexdoe', 'age' => 25}
console.log(map1.get('username')); // Outputs: alexdoeconst map1 = new Map();
map1.set('username', 'alexdoe');
map1.set('age', 25);
// Modifying the username now:
map1.set('username', 'janesmith');
console.log(map1.get('username')); // Outputs: janesmithMaps can be initialized with an array of arrays, each representing a key-value pair. We can pass them in Map constructor itself.
const map1 = new Map([
  ['username', 'alexdoe'],
  ['age', 25],
  ['country', 'USA'],
  ['city', 'New York']
]);
console.log(map1); // Map(4) {'username' => 'alexdoe', 'age' => 25, ...}To convert an object’s properties to Map key-value pairs, Object.entries() is used.
const user = { username: 'alexdoe', age: 25 };
const map1 = new Map(Object.entries(user));
console.log(map1); // Map(2) {'username' => 'alexdoe', 'age' => 25}Chain multiple set() calls thanks to its returning the Map object.
const map1 = new Map();
map1
.set('username', 'alexdoe')
.set('score', 95)
.set('status', 'active')
.set('city', 'New York');
console.log(map1); // Map(4) {'username' => 'alexdoe', 'score' => 95, ...}To avoid overwriting existing keys, use has() before set().
if (!map1.has('username')) {
map1.set('username', 'newuser');
}
console.log(map1.get('username')); // Outputs: alexdoe
Demonstrating the flexibility of Maps with various key types (like array, or even objects).
const map1 = new Map();
const keyObject = { id: 1 };
map1.set(keyObject, { profile: 'Developer' });
console.log(map1.get(keyObject)); // Outputs: { profile: 'Developer' }
delete(), clear(), and has() for effective Map management.map.forEach() or for…of loops to iterate over Maps.In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.
You’re given a Map containing some keys and values. Your task is to add a new key/value pair to this Map. However, the twist is, if the key already exists, append the new value to the existing one with a hyphen (
-) in between.
Problem:
/**
* Modifies the given Map by adding a new key/value pair or appending to an existing key's value.
*
* @param {Map} map - The original Map.
* @param {String} key - The key to be added or modified.
* @param {String} value - The value to be added or appended.
* @returns {Map} The modified Map.
*/
function modifyMap(map, key, value) {
  // > > > 👉 Write code here 👈 < < <
}
// Example usage
const myMap = new Map([['theme', 'dark'], ['language', 'JavaScript']]);
console.log("Original Map:", myMap);
// Console log before modification
// Adding a new key/value pair
modifyMap(myMap, 'framework', 'React');
console.log("Map after adding 'framework':", myMap);
// Should show React as value for 'framework'
// Modifying an existing key
modifyMap(myMap, 'theme', 'light');
console.log("Map after modifying 'theme':", myMap);
// Should show 'dark-light' as value for 'theme'Please attempt before seeing the Answer:
function modifyMap(map, key, value) {
  if (map.has(key)) {
      value = `${map.get(key)}-${value}`;
  }
  map.set(key, value);
  return map;
}Explanation:
myMap contains two key-value pairs.modifyMap is first called with 'framework', 'React', the key 'framework' does not exist in the map, so it’s simply added.'theme', 'light' finds that 'theme' already exists, so it appends 'light' to the existing value 'dark', resulting in 'dark-light'.May this post adds value to your javascript map handling. Keep coding! 🚀
Feel free to reach out!