1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS
1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS

Increment a Value in an Object or a Map in JavaScript

ReadTime: 5 minutes

In JavaScript, objects and maps are powerful data structures that allow you to store key-value pairs. When working with these data structures, you may need to increment a value associated with a specific key. In this guide, we’ll explore various methods to increment a value in an object or a map using JavaScript.


Increment a Value in an Object in JavaScript

Approach 1: Dot and Bracket Notation to increment value in object

To increment a value in an object, you can use dot or bracket notation. In the dot notation example, we directly access the property using a period, while in bracket notation, we use square brackets. This flexibility is handy, especially when dealing with keys that contain spaces or special characters.

javascript
// Using dot notation
obj.count = obj.count + 1 || 1;
console.log(obj.count); // πŸ‘‰οΈ 2

// Using bracket notation
obj['count'] = obj['count'] + 1 || 1;
console.log(obj.count); // πŸ‘‰οΈ 3
Using Dot and Bracket Notation to increment value in object

Approach 2: Nullish Coalescing Operator to increment value in object

Now, let’s introduce a more elegant approach using the nullish coalescing operator. Here, we utilize the nullish coalescing operator (??) to check if the property is defined. If it is, we increment it; otherwise, we initialize it to 1. Elegant, isn’t it?

javascript
const obj = {
  num: 1,
};

obj['num'] = (obj['num'] ?? 0) + 1;
console.log(obj.num); // πŸ‘‰οΈ 2
Using Nullish Coalescing Operator to increment value in object

Increment a Value in a Map using JavaScript

Now, let’s shift our focus to maps and discover how to gracefully increment values within this powerful data structure.

Approach 1: The Set Method to increment value in map

In this example, we leverage the set method of the Map class to update an existing key’s value or create a new key if it doesn’t exist. The logical OR (||) ensures proper initialization.

javascript
const map1 = new Map([['num', 1]]);
  
map1.set('num', map1.get('num') + 1 || 1);

console.log(map1.get('num')); // πŸ‘‰οΈ 2
Using Set to increment value in map

Approach 2: Nullish Coalescing Operator to increment value in map

Enjoy the elegance of nullish coalescing in a map context:

Just like in the object scenario, the nullish coalescing operator ensures a smooth incrementation process, handling undefined or null values with grace.

javascript
const map1 = new Map([['num', 1]]);
  
map1.set('num', (map1.get('num') ?? 0) + 1);

console.log(map1.get('num')); // πŸ‘‰οΈ 2
Using Nullish Coalescing operator for incrementing a value in map

πŸ§ͺPractice Coding Problem: Count Duplicate Values

In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.

Implement a function countDuplicates(map) that counts and returns the number of duplicate values in a map.

Problem (JavaScript)

javascript
function countDuplicates(map) {
  // > > > πŸ‘‰ Write code here πŸ‘ˆ < < <
}

const sampleMap = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 1],
  ['d', 3],
  ['e', 2],
]);

console.log(countDuplicates(sampleMap));
// Expected output πŸ‘‰: 2
Problem Code

Please attempt before seeing the Answer:

Solution
javascript
function countDuplicates(map) {
  const valueCount = new Map();

  // Count occurrences of each value in the map
  map.forEach((value) => {
      const count = valueCount.get(value) || 0;
      valueCount.set(value, count + 1);
  });

  // Count the number of values with occurrences greater than 1
  let duplicateCount = 0;
  valueCount.forEach((count) => {
      if (count > 1) {
          duplicateCount++;
      }
  });

  return duplicateCount;
}

// In this solution, we use an additional valueCount map to keep track of the occurrences of each value in the given map. We then iterate over the map, updating the count in valueCount for each value encountered.

// Finally, we iterate over valueCount to count the number of values that have occurrences greater than 1, indicating duplicates.

// Feel free to test the countDuplicates function with other maps to explore its functionality further. Happy coding! πŸš€
Solution Code

Conclusion:

There you have it! Incrementing values in JavaScript objects and maps is now well within your coding arsenal. Armed with dot and bracket notation, the nullish coalescing operator, and the mighty set method, you’re ready to conquer any coding challenge that comes your way.

Happy coding, and may your values always be on the rise! πŸš€

Contact

Feel free to reach out!