🎄 Get 20% off from our JavaScript course for the holidays! 🎄 # How to Find the Sum and Average of Elements in an Array in JavaScript

Ferenc Almasi • 2021 April 30 • 2 min read

If you need to compute the sum or the average of an array of elements in JavaScript, you can use `reduce` to get the shortest possible solution:

Copied to clipboard!
``````const fibonacci = [2, 3, 5];

// Will return 10
const sum = fibonacci.reduce((a, b) => a + b, 0);

// Will return 3.3333333333333335
const average = sum / fibonacci.length;``````
array-sum-and-average.js

If you are unsure whether the elements of the array are numbers, you can also cast them to one, using the built-in `Number` function:

Copied to clipboard!
``const sum = fibonacci.reduce((a, b) => (Number(a) + Number(b)) || 0, 0);``

## Explanation

Let's break this code down line-by-line so we fully understand how does it work. We start with this line:

Copied to clipboard!
``fibonacci.reduce((a, b) => a + b, 0);``

The `reduce` function takes in two arguments:

• A reducer function that you can define, that results in a single output for the element. This function has two mandatory arguments:
• The accumulator, denoted by `a`. This is the accumulated value returned from the last invocation of the callback.
• The current value, denoted by `b`, that is being processed in the array.
• Optionally, you can also provide an initial value that will be used as the first argument to your callback. In the example above, we provided an initial value of 0.

With the example array, these are the values of each argument, step by step:

Copied to clipboard!
``````[2, 3, 5].reduce((0, 2) => 0 + 2, 0); // First iteration  -> returns 2
[2, 3, 5].reduce((2, 3) => 2 + 3, 0); // Second iteration -> returns 5
[2, 3, 5].reduce((5, 5) => 5 + 5, 0); // Third iteration  -> returns 10``````

And to find the average, we can divide the sum by the number of numbers. In the second example, when we were unsure about whether we deal with numbers, we have the following:

Copied to clipboard!
``fibonacci.reduce((a, b) => (Number(a) + Number(b)) || 0, 0);``

But why do we need the `|| 0` at the end? This is because if either `a` or `b` cannot be converted to a number, the return value will be `NaN`. `NaN` + `NaN`, or `NaN` + any number will be returned as `NaN`, and we don't want that, so instead, we fall back to 0.

Copied to clipboard!
``````✅ Number('1') + Number('2') -> 1 + 2 -> 3
🔴 Number('a') + Number('b') -> NaN + NaN -> NaN``````  • Access exclusive interactive lessons
• Unlimited access to hundreds of tutorials
• Remove ads to learn without distractions