TheAlgorithms/JavaScript · error · TypeError

Input should be integer

Error message

Input should be integer

What it means

Thrown by fibonacci(N) as a TypeError when !Number.isInteger(N). The iterative implementation indexes by counting loop iterations, so fractional, NaN, Infinity, or non-number inputs are rejected before the loop runs.

Source

Thrown at Dynamic-Programming/FibonacciNumber.js:10

/**
 * @function fibonacci
 * @description Fibonacci is the sum of previous two fibonacci numbers.
 * @param {Integer} N - The input integer
 * @return {Integer} fibonacci of N.
 * @see [Fibonacci_Numbers](https://en.wikipedia.org/wiki/Fibonacci_number)
 */
const fibonacci = (N) => {
  if (!Number.isInteger(N)) {
    throw new TypeError('Input should be integer')
  }

  // memoize the last two numbers
  let firstNumber = 0
  let secondNumber = 1

  for (let i = 1; i < N; i++) {
    const sumOfNumbers = firstNumber + secondNumber
    // update last two numbers
    firstNumber = secondNumber
    secondNumber = sumOfNumbers
  }

  return N ? secondNumber : firstNumber
}

export { fibonacci }

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Sanitize at the call site: const n = Number(input); if (!Number.isInteger(n)) throw.
  2. Parse string inputs with parseInt(value, 10) and check the result.
  3. Provide a sensible default (e.g. 0) when the argument may be undefined.
  4. Reject negative integers explicitly if your use case does not support them.

Example fix

// before
const f = fibonacci(input) // throws on '7' / 3.2

// after
const n = Number(input)
if (!Number.isInteger(n)) throw new TypeError('N must be an integer')
const f = fibonacci(n)
Defensive patterns

Strategy: type-guard

Validate before calling

function safeFib(input) {
  const n = Number(input)
  if (!Number.isInteger(n)) {
    throw new TypeError('N must be an integer')
  }
  return fibonacci(n)
}

Type guard

const isInteger = (n) => Number.isInteger(n)

Try / catch

try {
  return fibonacci(n)
} catch (e) {
  if (e instanceof TypeError && /integer/i.test(e.message)) {
    return fibonacci(Math.trunc(Number(n)))
  }
  throw e
}

Prevention

When it happens

Trigger: fibonacci(3.2); fibonacci('7'); fibonacci(Infinity); fibonacci(undefined) (undefined is not an integer).

Common situations: Floats from user input or division; string values not parsed; default parameters of undefined when argument omitted.

Related errors


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