How To Get The Sum Of An Array Of Numbers In Typescript

How to get the sum of an Array of Numbers in Typescript

The For loop and reduce() method are simple ways to use to get the sum of an array of numbers in Typescript. So how to do it? Let’s go into detail to see the specific step!

Get the sum of an array of numbers in TypeScript

Here I want you to know the logic of the method. I will use different methods in all cases but still use one logic. I will create one variable to store the sum value, then loop over all elements of the number array. Then in each loop, I will plus the sum value with the current element. So let’s do it.

Use basic for loop

The most basic loop that you will learn in Typescript is for loop. The for loop have three expressions. The first is the expression that will be executed the first time for loop execution. The second is the condition that keeps the loop running. The third expression is the code that will be executed every time each loop is finished. You can read more about it here.


const numberArray = [1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,11 ,12 ,13]
let sumArray = 0

for (let i=0; i<numberArray.length; i++){
 sumArray+= numberArray[i]



[LOG]: 91

Here I use for loop with the initial value i, the condition is i lower than numberArray’ element length, each time the loop finish with increase i with 1. So here in the code block, i sum the sumArray variable with one element of numberArray i retrieve by passing index inside square braces then reassign to sumArray. So when the loop finishes, i will get the sum of all elements of numberArray.

Use reduce method

The reduce method a very typical to solve the calculate sum problems. With the reduce method, you can pass in a callback executed in each loop time. The reduce method also provided a parameter called the previous value to store the value of the previous loop, and the current value indicates the current element’s value. It is not easy to understand the first time you see it. You can read more about it here.


const numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

function caculateSum(preValue: number, currValue: number): number {
    preValue += currValue;
    return preValue;

const sum = numberArray.reduce(caculateSum, 0);


[LOG]: 91

Here preValue initialize is 0. What we return in each loop time will be stored in preValue. The reduce method will return the preValue after finishing the last loop time, so I create a variable call sum to store it.


In this article, I showed you how to get the sum of an array of numbers in Typescript. You can use basic for loop or can use reduce method. There are more methods, but I showed you some that are common. I hope it is helpful to you.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *