The average (arithmetic mean) of N numbers is their sum divided by the count.
Remember
average = (a₁ + a₂ + … + aₙ) / N
Example: 1, 2, 3, 4, 5
sum = 15, N = 5
average = 15 / 5 = 3
Values
Sum
N
Average
1, 2, 3, 4, 5
15
5
3
10, 15, 20, 25, 30
100
5
20
2, 4
6
2
3
1, 2
3
2
1.5
Approach
How to Find the Average of N Numbers in JavaScript
Sum every value once, then divide by the count — guard empty input first.
Reject N <= 0 or an empty array (no division by zero).
Iterate the N values (loop or reduce).
Accumulate a running sum.
Return sum / N.
Method
Idea
Time
Best for
Running sum + N
Loop N times with a fixed list
O(N)
Interviews, demos
Array helper
Sum values.length items
O(N)
Reusable default
Array.reduce
Sum in one expression
O(N)
Concise scripts
Pseudocode
Pseudocode
function Average(values):
n = length of values
if n == 0:
return error // or a documented sentinel
sum = 0
for each value in values:
sum = sum + value
return sum / n
Reference
Cheat Sheet
Keep these facts handy while writing the program.
Topic
Detail
Formula
average = sum / N
Guard
Never divide when N <= 0
JS numbers
Division keeps decimals (no int truncation)
Not median
Median needs sorting; average does not
1..5
sum 15 → average 3
Try it
Live Preview
Enter comma-separated numbers to see the sum, count, and average.
Comma-separated numbers. Tap a chip or type your own list.
Result
values = [1, 2, 3, 4, 5]
sum = 15, N = 5
average = 3
Code
JavaScript Programs
Start with a running-sum helper and fixed N. Then average any array by length, and finish with a concise reduce mean. Each example has a Try it Yourself editor.
Example 1 — Running Sum with Fixed N
Validate N, loop N times over a values list, keep a running total, then divide.
JavaScript
function averageOfNNumbers(n, values) {
if (n <= 0) {
return 0;
}
let total = 0;
for (let i = 0; i < n; i++) {
total += values[i];
}
return total / n;
}
const n = 5;
const values = [1, 2, 3, 4, 5];
const result = averageOfNNumbers(n, values);
console.log("The average of the entered numbers is: " + result);
JS numbers keep decimals, so 1 / 2 is 0.5, not truncated.
Sample 1…5 prints 3.
Example 2 — Average from an Array
Reusable helper: sum every element, then divide by length.
JavaScript
function averageFromArray(values) {
if (!values.length) {
return 0;
}
let total = 0;
for (let i = 0; i < values.length; i++) {
total += values[i];
}
return total / values.length;
}
const data = [10, 15, 20, 25, 30];
const avg = averageFromArray(data);
console.log("Average = " + avg);