TheAlgorithms/JavaScript · error · TypeError

Expected a number, received ${typeof precision}

Error message

Expected a number, received ${typeof precision}

What it means

Thrown by the second parameter guard in `sqrt(num, precision = 4)`. Although `precision` has a default of `4`, passing an explicit non-finite value (NaN, Infinity, a string, undefined bypassing the default via `sqrt(9, undefined)`) triggers the throw. The value drives the fixed iteration count `for (let i = 0; i < precision; i++)`, so it must be a finite number.

Source

Thrown at Maths/SquareRoot.js:14

/*
 * 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. Omit the second argument entirely to use the default `precision = 4`.
  2. Coerce with `Number(precision)` and confirm `Number.isFinite` before passing.
  3. When forwarding optional values, fall back: `sqrt(num, precision ?? 4)`.

Example fix

// before
sqrt(num, config.iterations) // config.iterations may be a string or undefined

// after
const p = Number(config.iterations)
sqrt(num, Number.isFinite(p) ? p : 4)
Defensive patterns

Strategy: validation

Validate before calling

const p = Number(precision)
if (!Number.isFinite(p)) {
  sqrt(num) // fall back to default precision = 4
} else {
  sqrt(num, p)
}

Type guard

const isOptionalFiniteNumber = (x) => x === undefined || (typeof x === 'number' && Number.isFinite(x))

Prevention

When it happens

Trigger: Call `sqrt(9, undefined)` (defeating the default), `sqrt(9, '4')`, `sqrt(9, NaN)`, `sqrt(9, Infinity)`, or pass a computed precision that came back NaN.

Common situations: Forwarding an optional config field that was undefined, accepting a precision from JSON config (string), or treating a '0 precision' edge case where the caller computes `1/0`.

Related errors


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