TheAlgorithms/JavaScript · error · TypeError

Expected a number, received ${typeof num}

Error message

Expected a number, received ${typeof num}

What it means

Thrown by the `sqrt(num, precision)` function (Newton's method square root) when `num` fails `Number.isFinite(num)`. The guard rejects NaN, +/-Infinity and every non-number type because the iterative refinement `sqrt -= (sqrt*sqrt - num)/(2*sqrt)` would otherwise divide by zero or propagate NaN. Pass a finite JavaScript number to clear the check.

Source

Thrown at Maths/SquareRoot.js:11

/*
 * Author: Rak Laptudirm
 *
 * https://en.wikipedia.org/wiki/Newton%27s_method
 *
 * Finding the square root of a number using Newton's method.
 */

function sqrt(num, precision = 4) {
  if (!Number.isFinite(num)) {
    throw new TypeError(`Expected a number, received ${typeof num}`)
  }
  if (!Number.isFinite(precision)) {
    throw new TypeError(`Expected a number, received ${typeof precision}`)
  }
  let sqrt = 1
  for (let i = 0; i < precision; i++) {
    sqrt -= (sqrt * sqrt - num) / (2 * sqrt)
  }
  return sqrt
}

export { sqrt }

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Coerce before calling: pass `Number(value)` and verify `Number.isFinite` first.
  2. If the source is a string from user input, parse explicitly with `parseFloat(value)` and validate the result.
  3. Provide an explicit default at the call site so `undefined` never reaches the function.

Example fix

// before
sqrt(formValue) // formValue is a string like '16'

// after
const n = Number(formValue)
if (!Number.isFinite(n)) throw new TypeError('formValue must be a finite number')
sqrt(n)
Defensive patterns

Strategy: type-guard

Validate before calling

const n = Number(num)
if (!Number.isFinite(n)) {
  throw new TypeError('num must be a finite number')
}
sqrt(n)

Type guard

const isFiniteNumber = (x) => typeof x === 'number' && Number.isFinite(x)

Prevention

When it happens

Trigger: Call `sqrt(undefined)`, `sqrt(null)`, `sqrt('16')`, `sqrt(NaN)`, `sqrt(Infinity)`, `sqrt({})`, `sqrt([4])`, or any value where `Number.isFinite` returns false as the first argument.

Common situations: Reading numeric values from HTML forms, CLI args or env vars (all strings), propagating an optional field that was never set, or piping output of a previous computation that returned NaN on bad input.

Related errors


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