Borislav Hadzhiev
Last updated: Oct 30, 2021
Check out my new book
To get the sum of all values in a Map
:
sum
variable and set it to 0
.forEach()
method to iterate over the Map
.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.
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:
Map
objectWe take the current value and add it to sum
, reassigning the variable.
Map
object, we have the total stored in the sum
variable.