TheAlgorithms/JavaScript · error · TypeError

Argument must be an Array

Error message

Argument must be an Array

What it means

The meanSquaredError function computes MSE between predicted and expected value arrays via element-wise iteration. Both arguments must be arrays; the guard checks this before the length-equality check. Non-array arguments trigger this error.

Source

Thrown at Maths/MeanSquareError.js:5

// Wikipedia: https://en.wikipedia.org/wiki/Mean_squared_error

const meanSquaredError = (predicted, expected) => {
  if (!Array.isArray(predicted) || !Array.isArray(expected)) {
    throw new TypeError('Argument must be an Array')
  }

  if (predicted.length !== expected.length) {
    throw new TypeError('The two lists must be of equal length')
  }

  let err = 0

  for (let i = 0; i < expected.length; i++) {
    err += (expected[i] - predicted[i]) ** 2
  }

  return err / expected.length
}

export { meanSquaredError }

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Ensure both arguments are arrays.
  2. Wrap single values in an array if comparing only one data point.
  3. Validate with Array.isArray() for both arguments before calling.

Example fix

// before
meanSquaredError(42, expected)
// after
meanSquaredError([42], expected)
Defensive patterns

Strategy: type-guard

Validate before calling

if (!Array.isArray(predicted) || !Array.isArray(expected)) {
  throw new TypeError('Both arguments must be arrays')
}
meanSquaredError(predicted, expected)

Type guard

const areBothArrays = (a, b) => Array.isArray(a) && Array.isArray(b)

Prevention

When it happens

Trigger: Calling meanSquaredError("123", [1,2,3]), meanSquaredError([1,2], null), or passing a single number instead of an array for either argument.

Common situations: Passing a single prediction instead of an array of predictions, JSON deserialization type mismatches, or variables that were expected to be arrays but are undefined.

Related errors


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