Get the Sum of an Array of Numbers in TypeScript

avatar

Borislav Hadzhiev

Tue Mar 08 20222 min read

banner

Photo by Joel

Get the Sum of an Array of Numbers in TypeScript #

To get the sum of an array of numbers:

  1. Use the reduce() method to iterate over the array
  2. On each iteration, increment the accumulated sum with the current value.
  3. The result will be the sum of all the numbers in the array.
index.ts
const arr: number[] = [10, 20, 50]; const result = arr.reduce((accumulator, current) => { return accumulator + current; }, 0); console.log(result); // 👉️ 80

The function we passed to the Array.reduce method gets invoked with each element (number) in the array.

The accumulator parameter gets an initial value of 0, because that's what we supplied as the second parameter to the reduce method.

With each iteration, we increment the accumulator with the current value of the array until we calculate the total.

The reduce() method returns the sum of all of the numbers in the array.

You might also see examples that explicitly set the accumulator and return type of the reduce() method.

index.ts
const arr: number[] = [10, 20, 50]; // 👇️ using <number> generic to set return type const result = arr.reduce<number>((accumulator, current) => { return accumulator + current; }, 0); console.log(result); // 👉️ 80

The example above uses a generic to explicitly set the type for the accumulator variable and the return type of the reduce() method.

However, in this situation it can be omitted, as TypeScript is able to infer it based on the provided default value.

An alternative and perhaps simpler approach is to use the forEach method.

To get the sum of an array of numbers:

  1. Initialize a sum variable, using the let keyword and set it to 0.
  2. Call the forEach() method to iterate over the array.
  3. On each iteration, increment the sum variable with the current number.
index.ts
const arr: number[] = [10, 20, 50]; let sum = 0; arr.forEach((element) => { sum += element; }); console.log(sum); // 👉️ 80

The function we pass to the Array.forEach method gets called with each element in the array.

Notice that we declare the sum variable using the let keyword. We can't reassign variables declared using const.

On each iteration of the loop, we increment the value stored in the sum variable to get the total amount.

This approach is more readable and intuitive, especially if you're not used to how the reduce method works.

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