- Sum
1 + 2 + 3 + 4 + 5 = 15- Count
N = 5- Mean
15 / 5 = 3(matches the sample script output).
Find Average of N Numbers in JavaScript
What you’ll learn
- The arithmetic mean formula and how it maps to a running sum in JavaScript.
- A pattern that mirrors “read
Nvalues then divide” using a callback or array index, plus a pure array average helper. - Why you still guard
N === 0, validate withNumber.isFinite, and when IEEE-754 rounding matters. - A browser live preview for comma-separated numbers (same math as the samples).
Overview
This walkthrough shows how to treat N numeric inputs, accumulate their sum, and print the average (mean). A second script averages values already stored in an array—the same math, a different data path.
Two scripts
Indexed reads for N values (mirrors a stdin loop), plus a fixed array example (same mean idea).
Live preview
Paste comma-separated values and see count, sum, and mean instantly.
Interview polish
Guards for N ≤ 0, NaN from parsing, and notes on floating-point summation at scale.
Prerequisites
You should know basic for loops, JavaScript arrays, and how Number parsing relates to NaN.
forloops, function parameters, and formatting withtoFixedfor readable console output.- Optional: read automorphic numbers for another digit-focused interview pattern.
What is the average here?
The arithmetic mean (what we call average on this page) of numbers x1, …, xN is
μ = (x1 + x2 + … + xN) / N, provided N > 0.
In code you usually maintain one accumulator sum inside a loop, then divide once at the end.
Formal definition
Given real numbers x1, …, xN with N ≥ 1, the sample mean is μ = (1/N) Σi=1N xi.
For 10, 15, 20, 25, 30, the sum is 100 and N = 5, so μ = 100 / 5 = 20.
The reference prose used this list; it is a clean sanity check when you print intermediate sums during debugging.
Intuition and examples
Think of the mean as “flattening” every value onto one number: if you replaced every entry in the list with that number, the total would match the original sum.
- Sum
10 + 15 + 20 + 25 + 30 = 100- Count
N = 5- Mean
100 / 5 = 20.
- Division
- Plain
/onNumberis floating-point (unlike Cint/int). - Still watch
- Tiny rounding after many additions; use compensated summation or decimals for money.
- Always
- Guard
N === 0and reject non-finite parsed values.
Takeaway: the math is simple; most bugs are empty counts, NaN input, or precision policy—not the formula itself.
Live preview
Enter numbers separated by commas (spaces optional). The tool parses each token as a JavaScript number, sums them, divides by the count, and prints count, sum, and mean. Empty input is rejected; at most 500 values are accepted.
- Try
1, 2, 3, 4, 5or10,15,20,25,30. - Press Run (or Enter).
- Compare with your script output for the same list.
Algorithm
Goal: read N values, compute their arithmetic mean.
Read N
Decide how many numbers will be averaged. If N ≤ 0, stop or report an error before dividing.
Initialize sum = 0
Use a Number accumulator (or BigInt if your domain requires integers only).
Loop N times
Each iteration obtains one value (from stdin, an array, a generator, or async source) and adds it to sum after validating it is finite.
Divide
Return sum / N for Number data. JavaScript promotes to floating division automatically for normal numbers.
📜 Pseudocode
function averageOfN(n):
if n <= 0:
return error
sum ← 0
repeat n times:
read x
sum ← sum + x
return sum / nAverage of N numbers (indexed reads)
Uses a small readOne(i) callback so the summation loop matches the classic “read N times” shape. The sample wires it to a literal array [1,2,3,4,5]; in Node you could read from process.argv or readline instead.
/**
* @param {number} n how many values to average
* @param {(index: number) => number} readOne returns i-th value (0-based)
* @returns {number} mean, or 0 if n <= 0 or a non-finite value appears
*/
function findAverage(n, readOne) {
if (n <= 0) {
return 0;
}
let sum = 0;
for (let i = 0; i < n; i++) {
const x = readOne(i);
if (!Number.isFinite(x)) {
return 0;
}
sum += x;
}
return sum / n;
}
const n = 5;
const inputs = [1, 2, 3, 4, 5];
const result = findAverage(n, (i) => inputs[i]);
console.log("The average of the entered numbers is:", result.toFixed(6));Explanation
The function keeps one running total and only divides after every term has been read.
if (n <= 0) return 0;Guard division. Avoids Infinity or NaN from dividing by zero.
readOne(i)Pluggable input. Swap the callback for prompts, file lines, or stream chunks without changing the mean logic.
return sum / n;Floating mean. JavaScript uses IEEE-754 doubles here; format with toFixed when you need a stable display.
Average from a fixed array
Same mean as the formal example: 10, 15, 20, 25, 30 → mean 20. Useful when inputs are already in memory (API JSON, typed arrays, etc.).
/**
* @param {number[] | null | undefined} a
* @returns {number} mean, or 0 if missing / empty
*/
function averageFromArray(a) {
if (!a || a.length === 0) {
return 0;
}
const n = a.length;
let sum = 0;
for (let i = 0; i < n; i++) {
const x = a[i];
if (!Number.isFinite(x)) {
return 0;
}
sum += x;
}
return sum / n;
}
const data = [10, 15, 20, 25, 30];
const avg = averageFromArray(data);
console.log("Average =", avg.toFixed(6));Explanation
a.length supplies N; the loop is the same running-sum pattern as Example 1.
if (!a || a.length === 0)Defensive API. Treats null, undefined, and empty lists like the invalid-count case.
Number.isFinite(x)Reject bad cells. Stops if any element is NaN or non-finite (mirrors checking scanf in C).
Optimization
One pass. You never need to store all values just to compute the mean; a running sum is enough unless other statistics are required.
Very large N or huge magnitudes. Kahan summation or decimal libraries reduce rounding error; for money, avoid raw binary floats.
Online mean. If values arrive in a stream, update with meank = meank-1 + (xk - meank-1) / k to avoid storing the full history.
Interview: state O(N) time and O(1) extra space for the streaming sum approach.
❓ FAQ
🔄 Input / output examples
For Example 1, change n and the inputs array together, or replace readOne with logic that reads from process.argv slice or a prompt in the browser.
| Sample inputs (first script) | Printed line (example) |
|---|---|
n = 5, [1,2,3,4,5] | The average of the entered numbers is: 3.000000 |
n = 5, [10,15,20,25,30] | The average of the entered numbers is: 20.000000 |
n = 2, [2.5, 3.5] | The average of the entered numbers is: 3.000000 |
Example 2 prints a single line:
Average = 20.000000Edge cases and pitfalls
Most real-world bugs are about empty lists, NaN, divide-by-zero, or precision policy—not the formula itself.
N === 0
Never divide until you know the count is positive.
NaN and Infinity
Coercion surprises (Number("") === 0) and bad JSON can poison the sum. Prefer explicit parsing plus Number.isFinite.
Async sources
If values arrive asynchronously, either buffer then average or use an online formula; do not mix await inside a naive synchronous loop without structuring it.
Huge sums
For extreme magnitudes, Number loses integer precision past 253-1; consider BigInt or a decimal library.
⏱️ Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
Running sum over N inputs | O(N) | O(1) |
| Store all values then sum | O(N) | O(N) for the buffer |
Both sample scripts on this page use only a few scalars beyond the input array: auxiliary space is constant relative to extra structures.
Summary
- Mean: add all values, divide by
NforN > 0. - Code: running
sum, pluggablereadOneor array scan, divide with/on finite numbers. - Watch-outs:
N === 0,NaNinputs, async ordering, and float policy for money-scale data.
The arithmetic mean is the simplest “center” of a list: add every value, divide by how many there are. In JavaScript, division of two Number values is floating-point—unlike C’s int / int trap—but you still must guard N === 0 and watch NaN from bad input.
9 people found this page helpful
