TheAlgorithms/JavaScript · error · TypeError

Arguments must be numbers

Error message

Arguments must be numbers

What it means

Thrown by the internal CheckInput(a, b) helper (GetEuclidGCD.js:1) as a TypeError when either a or b is not of type 'number'. GetEuclidGCD calls CheckInput at the start of every invocation before applying Math.abs and running the Euclidean algorithm. Note the helper only checks type, not finiteness or integer-ness — NaN is typeof 'number' and passes, and floats are accepted (the algorithm will still run). The GCD of NaN inputs is NaN.

Source

Thrown at Maths/GetEuclidGCD.js:3

function CheckInput(a, b) {
  if (typeof a !== 'number' || typeof b !== 'number') {
    throw new TypeError('Arguments must be numbers')
  }
}

/**
 * GetEuclidGCD Euclidean algorithm to determine the GCD of two numbers
 * @param {Number} a integer (may be negative)
 * @param {Number} b integer (may be negative)
 * @returns {Number} Greatest Common Divisor gcd(a, b)
 */
export function GetEuclidGCD(a, b) {
  CheckInput(a, b)
  a = Math.abs(a)
  b = Math.abs(b)
  while (b !== 0) {
    const rem = a % b
    a = b
    b = rem
  }

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Coerce both arguments with Number() and verify with Number.isFinite before calling — the helper does not reject NaN.
  2. Add a stronger guard than the library's own check if you need to exclude NaN, Infinity, or non-integers.
  3. Catch TypeError at the boundary since this function throws TypeError.
  4. Ensure both arguments are supplied — there are no defaults.

Example fix

// before
const g = GetEuclidGCD(a, b) // a or b may be a string or undefined

// after
const [x, y] = [a, b].map(Number)
if (![x, y].every(Number.isFinite)) throw new TypeError('expected finite numbers')
const g = GetEuclidGCD(x, y)
Defensive patterns

Strategy: type-guard

Validate before calling

const [x, y] = [a, b].map(Number)
if (![x, y].every(v => Number.isFinite(v))) {
  throw new TypeError('both arguments must be finite numbers')
}
const g = GetEuclidGCD(x, y)

Type guard

const areFiniteNumbers = (...vals) => vals.every(v => typeof v === 'number' && Number.isFinite(v))

Try / catch

try {
  g = GetEuclidGCD(a, b)
} catch (e) {
  if (e instanceof TypeError && e.message === 'Arguments must be numbers') {
    // non-number input — coerce with Number() and retry
  } else throw e
}

Prevention

When it happens

Trigger: Call GetEuclidGCD('12', 8) with a string; GetEuclidGCD(undefined, 8) from a missing argument; GetEuclidGCD(null, 8) where null is typeof 'object'; GetEuclidGCD([12], 8) passing an array.

Common situations: Form or CLI inputs parsed as strings; optional parameters that arrived undefined; values pulled from JSON where numbers were quoted; BigInt inputs (typeof 'bigint').

Related errors


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