Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Array Average in JavaScript

Find the average of an array in JavaScript with a loop, reduce and forEach. Learn to guard an empty array against divide by zero. Explanation and output.

BeginnerJavaScript Array ProgramsExample 2 of 6
array-average.js
1// Method 1: Using for loop
2function averageLoop(arr) {
3 if (arr.length === 0) return 0;
4
5 let sum = 0;
6 for (let i = 0; i < arr.length; i++) {
7 sum += arr[i];
8 }
9 return sum / arr.length;
10}
11
12let numbers = [10, 20, 30, 40, 50];
13console.log("Array:", numbers);
14console.log("Average:", averageLoop(numbers));
15
16// Method 2: Using reduce
17function averageReduce(arr) {
18 if (arr.length === 0) return 0;
19
20 let sum = arr.reduce((acc, num) => acc + num, 0);
21 return sum / arr.length;
22}
23
24console.log("\nUsing reduce:", averageReduce([5, 10, 15, 20]));
25
26// Method 3: Using forEach
27function averageForEach(arr) {
28 if (arr.length === 0) return 0;
29
30 let sum = 0;
31 arr.forEach(num => sum += num);
32 return sum / arr.length;
33}
34
35console.log("\nUsing forEach:", averageForEach([2, 4, 6, 8, 10]));
36
37// Method 4: One-liner with reduce
38const average = arr => arr.length ? arr.reduce((a, b) => a + b) / arr.length : 0;
39
40console.log("\nOne-liner:", average([1, 2, 3, 4, 5]));
41
42// Method 5: With precision
43function averagePrecise(arr, decimals = 2) {
44 if (arr.length === 0) return 0;
45 let avg = arr.reduce((a, b) => a + b) / arr.length;
46 return parseFloat(avg.toFixed(decimals));
47}
48
49console.log("\nWith precision:", averagePrecise([1, 2, 3], 2));

Sample Output

Array: [ 10, 20, 30, 40, 50 ]
Average: 30

Using reduce: 12.5

Using forEach: 6

One-liner: 3

With precision: 2

In this one

  • How to compute an average
  • Why an empty array must be checked
  • How reduce keeps a running total
  • How to round an average to fixed decimals

How it works

  1. 1

    averageLoop adds [10..50] to 150 and divides by 5, giving 30.

  2. 2

    averageReduce gives 50 / 4 = 12.5.

  3. 3

    averageForEach gives 30 / 5 = 6.

  4. 4

    The one-liner gives 3 and averagePrecise gives 2.

Edge cases

Empty array

Without the guard, the result is NaN.

The guard returns 0 before dividing.

Strings in the array

["10", "20"] reduced from 0 gives "01020".

Convert values with Number() before adding.

Rounding

averagePrecise([1, 2, 2], 2) gives 1.67.

toFixed rounds for display. parseFloat removes extra zeros.

What's going on

The average, or mean, is the sum of all values divided by how many there are. A teacher uses it to find the class average from a list of marks.

Every method follows two steps. Add the numbers, then divide by arr.length.

Each function begins with if (arr.length === 0) return 0. This guard matters. Dividing by zero does not crash in JavaScript. Instead you get NaN when the sum is 0 too, since 0 / 0 is NaN. NaN means Not a Number. That strange value then spreads into every later calculation. Returning 0 is one choice. Returning null is clearer if "no data" should look different from a real average of 0.

Method 1 adds with a for loop. Method 2 uses reduce((acc, num) => acc + num, 0). reduce walks the array and keeps a running total in acc, which starts at 0. Method 3 uses forEach and adds to an outside variable.

Method 4 is a one-liner. It uses a ternary to check length and reduce to add. Note it calls reduce without a start value. That is safe here only because the length check runs first.

Method 5 rounds with toFixed(decimals), then wraps it in parseFloat to turn the string back into a number. The average of [1, 2, 3] is 2, so it prints 2, not 2.00.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is the average of [4, 8, 12]?

Pick an answer to check it.

Question 2

What is 0 / 0 in JavaScript?

Pick an answer to check it.

Questions people ask

Should an empty array return 0 or null?

null is clearer when you need to show "no data". This program uses 0 for simplicity.

Why does the one-liner not need a start value?

reduce uses the first item as the start, and the length check stops it from running on an empty array.

Can I average only passing marks?

Yes. filter first, then average the filtered array.