Array Average

Program to calculate average of array elements

BeginnerTopic: Array Programs
Back

JavaScript Array Average Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// Method 1: Using for loop
function averageLoop(arr) {
    if (arr.length === 0) return 0;
    
    let sum = 0;
    for (let i = 0; i < arr.length; i++) {
        sum += arr[i];
    }
    return sum / arr.length;
}

let numbers = [10, 20, 30, 40, 50];
console.log("Array:", numbers);
console.log("Average:", averageLoop(numbers));

// Method 2: Using reduce
function averageReduce(arr) {
    if (arr.length === 0) return 0;
    
    let sum = arr.reduce((acc, num) => acc + num, 0);
    return sum / arr.length;
}

console.log("\nUsing reduce:", averageReduce([5, 10, 15, 20]));

// Method 3: Using forEach
function averageForEach(arr) {
    if (arr.length === 0) return 0;
    
    let sum = 0;
    arr.forEach(num => sum += num);
    return sum / arr.length;
}

console.log("\nUsing forEach:", averageForEach([2, 4, 6, 8, 10]));

// Method 4: One-liner with reduce
const average = arr => arr.length ? arr.reduce((a, b) => a + b) / arr.length : 0;

console.log("\nOne-liner:", average([1, 2, 3, 4, 5]));

// Method 5: With precision
function averagePrecise(arr, decimals = 2) {
    if (arr.length === 0) return 0;
    let avg = arr.reduce((a, b) => a + b) / arr.length;
    return parseFloat(avg.toFixed(decimals));
}

console.log("\nWith precision:", averagePrecise([1, 2, 3], 2));
Output
Array: [ 10, 20, 30, 40, 50 ]
Average: 30

Using reduce: 12.5

Using forEach: 6

One-liner: 3

With precision: 2

Understanding Array Average

This program demonstrates different methods to calculate the average of array elements.

Average Formula

Average = Sum of all elements / Number of elements

Method 1: For Loop

Traditional iterative approach:

let sum = 0;
for (let i = 0; i < arr.length; i++) {
    sum += arr[i];
}
return sum / arr.length;

Method 2: Reduce

Functional approach:

let sum = arr.reduce((acc, num) => acc + num, 0);
return sum / arr.length;

Reduce Syntax:

arr.reduce((accumulator, currentValue) => {
}, initialValue);
    // return new accumulator

Method 3: ForEach

Iterate and accumulate:

let sum = 0;
arr.forEach(num => sum += num);
return sum / arr.length;

ForEach vs For Loop:

ForEach: Functional, can't break
For loop: Can break/continue, more control

Method 4: Arrow Function One-Liner

Concise ES6 syntax:

const average = arr => arr.length ? arr.reduce((a, b) => a + b) / arr.length : 0;

Ternary Operator:

Checks if array has elements
Returns 0 if empty (avoid division by zero)

Method 5: With Precision

Control decimal places:

return parseFloat(avg.toFixed(decimals));

Number Methods:

toFixed(n): Rounds to n decimals, returns string
parseFloat(): Converts string to number

Edge Cases:

Empty array: Return 0 or handle error
Single element: Returns that element
Negative numbers: Works normally

When to Use:

-

Loop

: Learning, simple

-

Reduce

: Modern, functional

-

One-liner

: Quick calculations

-

Precise

: When decimal control needed

Let us now understand every line and the components of the above program.

Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.

Practical Learning Notes for Array Average

This JavaScript program is part of the "Array Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents