TheAlgorithms/JavaScript · warning · Error

Array is empty

Error message

Array is empty

What it means

Thrown by mean(numbers) (AverageMean.js:15) as a plain Error when the input array has length 0. The mean of an empty set is mathematically undefined (division by zero would yield NaN), so the library rejects it explicitly. This is distinct from the non-array TypeError and is thrown as Error, so a catch clause targeting only TypeError will miss it.

Source

Thrown at Maths/AverageMean.js:16

/**
 * @function mean
 * @description This script will find the mean value of a array of numbers.
 * @param {number[]} numbers - Array of integer
 * @return {number} - mean of numbers.
 * @throws {TypeError} If the input is not an array or contains non-number elements.
 * @throws {Error} If the input array is empty.
 * @see [Mean](https://en.wikipedia.org/wiki/Mean)
 * @example mean([1, 2, 4, 5]) = 3
 * @example mean([10, 40, 100, 20]) = 42.5
 */
const mean = (numbers) => {
  if (!Array.isArray(numbers)) {
    throw new TypeError('Invalid Input')
  } else if (numbers.length === 0) {
    throw new Error('Array is empty')
  }

  let total = 0
  numbers.forEach((num) => {
    if (typeof num !== 'number') {
      throw new TypeError('Invalid Input')
    }
    total += num
  })

  return total / numbers.length
}

export { mean }

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Check numbers.length before calling and return a sensible default (null, 0, or NaN) for empty input.
  2. Ensure upstream filters and queries are not over-constrained.
  3. Wrap in try/catch for plain Error if empty input is a recoverable condition in your domain.
  4. Validate the data source returned at least one record before computing the mean.

Example fix

// before
const m = mean(filtered) // throws if filtered is []

// after
const m = filtered.length === 0 ? NaN : mean(filtered)
Defensive patterns

Strategy: validation

Validate before calling

if (!Array.isArray(numbers) || numbers.length === 0) {
  return NaN // or a domain-appropriate default
}
const m = mean(numbers)

Type guard

const isNonEmptyArray = (v) => Array.isArray(v) && v.length > 0

Try / catch

try {
  m = mean(numbers)
} catch (e) {
  if (e instanceof Error && e.message === 'Array is empty') {
    m = NaN
  } else throw e
}

Prevention

When it happens

Trigger: Call mean([]) directly; pass a filtered array that happened to retain zero elements (e.g. mean(arr.filter(x => x > 100)) when nothing matches); pass an array populated from an empty database result set.

Common situations: Filtering or slicing data that unexpectedly yields no elements; empty CSV import; time-windowed aggregations over a period with no events; default parameter that was set to [] but never populated.

Related errors


AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13). Data as JSON: /api/errors/56e9a8644cffc593. Report an issue: GitHub.