Find Average of N Numbers in JavaScript

Beginner
⏱️ 10 min read
📚 Updated: May 2026
🎯 2 Code examples + Try it
Loops & arrays

What you’ll learn

  • The arithmetic mean formula and how it maps to a running sum in JavaScript.
  • A pattern that mirrors “read N values then divide” using a callback or array index, plus a pure array average helper.
  • Why you still guard N === 0, validate with Number.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.

  • for loops, function parameters, and formatting with toFixed for 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.

Mean sum ÷ count
Median middle after sort
Mode most frequent

Formal definition

Given real numbers x1, …, xN with N ≥ 1, the sample mean is μ = (1/N) Σi=1N xi.

Worked example

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.

1 – 5 Mean 3
Sum
1 + 2 + 3 + 4 + 5 = 15
Count
N = 5
Mean
15 / 5 = 3 (matches the sample script output).
10 – 30 Mean 20
Sum
10 + 15 + 20 + 25 + 30 = 100
Count
N = 5
Mean
100 / 5 = 20.
JS IEEE-754
Division
Plain / on Number is floating-point (unlike C int/int).
Still watch
Tiny rounding after many additions; use compensated summation or decimals for money.
Always
Guard N === 0 and 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.

  1. Try 1, 2, 3, 4, 5 or 10,15,20,25,30.
  2. Press Run (or Enter).
  3. Compare with your script output for the same list.

Uses normal JavaScript floating point (not arbitrary precision).

Live result
Press “Run” to see count, sum, and mean.

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

Pseudocode
function averageOfN(n):
    if n <= 0:
        return error
    sum ← 0
    repeat n times:
        read x
        sum ← sum + x
    return sum / n
1

Average 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.

JavaScript
/**
 * @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));
Try it Yourself

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.

2

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.).

JavaScript
/**
 * @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));
Try it Yourself

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

Add all N values into an accumulator, then divide by N. With an array you can use a for loop or reduce: mean = sum / arr.length. Always check length > 0 before dividing.
For normal Number values, / is always floating-point (3/2 is 1.5). Truncation bugs appear if you intentionally floor, use bitwise tricks, or mix BigInt with Number incorrectly.
Division by zero yields Infinity or NaN depending on the numerator. Validate count > 0 before dividing, or return null / throw in strict APIs.
After parsing with Number(), parseFloat(), or unary +, use Number.isFinite() to reject NaN and non-finite values. Empty strings and stray commas need explicit handling.
One pass over N values is O(N) time. A running sum uses O(1) extra space; materializing all values in an array is O(N) space.
No. The mean is sum divided by count. The median is the middle value after sorting (or the average of the two middle values). They measure different notions of center.

🔄 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:

Console
Average = 20.000000

Edge cases and pitfalls

Most real-world bugs are about empty lists, NaN, divide-by-zero, or precision policy—not the formula itself.

Zero

N === 0

Never divide until you know the count is positive.

Types

NaN and Infinity

Coercion surprises (Number("") === 0) and bad JSON can poison the sum. Prefer explicit parsing plus Number.isFinite.

I/O

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.

Overflow

Huge sums

For extreme magnitudes, Number loses integer precision past 253-1; consider BigInt or a decimal library.

⏱️ Time and space complexity

ApproachTimeExtra space
Running sum over N inputsO(N)O(1)
Store all values then sumO(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 N for N > 0.
  • Code: running sum, pluggable readOne or array scan, divide with / on finite numbers.
  • Watch-outs: N === 0, NaN inputs, async ordering, and float policy for money-scale data.
Did you know?

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.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful