How to Sum the Values of an Object in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 14 20212 min read

banner

Photo by Justin Luebke

Sum the Values of an Object #

To sum the values of an object:

  1. Declare a sum variable using the let keyword and set it to 0.
  2. Use the for...in loop to iterate over the object's properties and on each iteration increment the sum variable with the current value.
index.js
const obj = { one: 5, two: 15, three: 45, }; let sum = 0; for (const key in obj) { sum += obj[key]; } console.log(sum); // ๐Ÿ‘‰๏ธ 65

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

The for...in loop iterates over the object's properties and allows us to access each value.

Once the loop has iterated over all of the object's properties we have the sum of the values.

An alternative approach is to use the reduce method.

To sum the values of an object:

  1. Get an array of the object's values by using the Object.values() method.
  2. Use the reduce method to iterate over the array of values and add each value to the sum.
index.js
const obj = { one: 5, two: 15, three: 45, }; // ๐Ÿ‘‡๏ธ [5, 15, 45] const values = Object.values(obj); const sum = values.reduce((accumulator, value) => { return accumulator + value; }, 0); console.log(sum); // ๐Ÿ‘‰๏ธ 65

We used the Object.values method to get an array containing the object's values.

The initial value for the accumulator is 0, because that's what we passed as the second parameter to the reduce method.

On each iteration, we increment the accumulator with the current value to get the sum of values.

The Object.values method is not supported in Internet Explorer versions 6-11. If you have to support the browser, use the for...in loop approach instead.

An alternative and perhaps simpler approach is to use a for...of loop instead of reduce.

To sum the values of an object:

  1. Declare a sum variable using the let keyword and set it to 0.
  2. Get an array of the Object's values, using the Object.values() method.
  3. Use the for...of loop to iterate over the object's values and on each iteration increment the sum variable with the current value.
index.js
const obj = { one: 5, two: 15, three: 45, }; let sum = 0; for (const value of Object.values(obj)) { sum += value; } console.log(sum); // ๐Ÿ‘‰๏ธ 65

The for...of loop allows us to iterate over an array.

We use the Object.values method to get an array of the object's values and then increment the sum variable on each iteration.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee