Get the Sum of all Values in a Map using JavaScript


Borislav Hadzhiev

Last updated: Oct 30, 2021


Check out my new book

Get the Sum of all Values in a Map #

To get the sum of all values in a Map:

  1. Initialize a sum variable and set it to 0.
  2. Use the forEach() method to iterate over the Map.
  3. On each iteration, add the number to the sum, reassigning the variable.
const map1 = new Map([ ['key1', 1], ['key2', 2], ]); let sum = 0; map1.forEach(value => { sum += value; }); console.log(sum); // 👉️ 3

The forEach method returns undefined, so we need to declare a variable where we can keep the state.

Notice that we used the let keyword to declare the sum variable, had we used const, we wouldn't be able to reassign it.

We used the Map() constructor to create a Map object that consists of 2 key-value pairs.

The function we passed to the Map.forEach method gets called with 3 parameters:

  • the value of the iteration
  • the key of the iteration
  • the Map object

We take the current value and add it to sum, reassigning the variable.

Once the function iterates over the entire Map object, we have the total stored in the sum variable.

Further Reading #

Use the search field on my Home Page to filter through my more than 3,000 articles.