TheAlgorithms/JavaScript · error · Error

Input data must be numbers

Error message

Input data must be numbers

What it means

Thrown by `squareRootLogarithmic(num)` when `typeof num !== 'number'`. The function uses binary search between 0 and `num`, so a non-number would break the loop arithmetic. Note the guard only checks `typeof`, so NaN (which is technically `typeof === 'number'`) slips through and yields an incorrect answer rather than this error.

Source

Thrown at Maths/SquareRootLogarithmic.js:20

 * @function squareRootLogarithmic
 * @description
 * Return the square root of 'num' rounded down
 * to the nearest integer.
 * More info: https://leetcode.com/problems/sqrtx/
 * @param {Number} num Number whose square of root is to be found
 * @returns {Number} Square root
 * @see [BinarySearch](https://en.wikipedia.org/wiki/Binary_search_algorithm)
 * @example
 * const num1 = 4
 * logarithmicSquareRoot(num1) // ====> 2
 * @example
 * const num2 = 8
 * logarithmicSquareRoot(num1) // ====> 2
 *
 */
const squareRootLogarithmic = (num) => {
  if (typeof num !== 'number') {
    throw new Error('Input data must be numbers')
  }
  let answer = 0
  let sqrt = 0
  let edge = num

  while (sqrt <= edge) {
    const mid = Math.trunc((sqrt + edge) / 2)
    if (mid * mid === num) {
      return mid
    } else if (mid * mid < num) {
      sqrt = mid + 1
      answer = mid
    } else {
      edge = mid - 1
    }
  }

  return answer

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Coerce with `Number(num)` and reject NaN explicitly before calling.
  2. If your input is a string, `parseFloat` and validate the result is finite.
  3. Add a `Number.isFinite` check upstream so NaN never reaches this function.

Example fix

// before
squareRootLogarithmic(payload.value) // payload.value may be '16'

// after
const v = Number(payload.value)
if (!Number.isFinite(v)) throw new TypeError('value must be a finite number')
squareRootLogarithmic(v)
Defensive patterns

Strategy: type-guard

Validate before calling

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

Type guard

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

Prevention

When it happens

Trigger: Call `squareRootLogarithmic('16')`, `squareRootLogarithmic(null)`, `squareRootLogarithmic(undefined)`, `squareRootLogarithmic(BigInt(16))`. Passing NaN does NOT throw (it returns NaN).

Common situations: JSON-parsed input where numbers arrive as strings, BigInt arithmetic mixed with Number, or unguarded destructuring from an object whose field was absent.

Related errors


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