TheAlgorithms/JavaScript · error · TypeError

Index cannot be a Decimal

Error message

Index cannot be a Decimal

What it means

The lucas function requires an integer index because it uses a for-loop counter (i < index) that would not terminate correctly with a fractional value. The guard compares Math.floor(index) !== index to detect non-integers, firing after the negative check.

Source

Thrown at Maths/LucasSeries.js:22

  Examples:
    > loopLucas(1)
    1
    > loopLucas(20)
    15127
    > loopLucas(100)
    792070839848372100000
*/

/**
 * @param {Number} index The position of the number you want to get from the Lucas Series
 */
function lucas(index) {
  // index can't be negative
  if (index < 0) throw new TypeError('Index cannot be Negative')

  // index can't be a decimal
  if (Math.floor(index) !== index)
    throw new TypeError('Index cannot be a Decimal')

  let a = 2
  let b = 1
  for (let i = 0; i < index; i++) {
    const temp = a + b
    a = b
    b = temp
  }
  return a
}

export { lucas }

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Pass an integer index to lucas.
  2. Apply Math.floor() or Math.round() to computed indices before calling if truncation/rounding is intended.
  3. Validate Number.isInteger(index) before calling.

Example fix

// before
lucas(total / 2)
// after
lucas(Math.floor(total / 2))
Defensive patterns

Strategy: validation

Validate before calling

if (!Number.isInteger(index)) {
  throw new TypeError('index must be an integer')
}
lucas(index)

Type guard

const isIntegerIndex = (i) => typeof i === 'number' && Number.isInteger(i)

Prevention

When it happens

Trigger: Calling lucas(2.5) or lucas(3.1). Any fractional index triggers this error. Division results like 7/2 passed directly as the index are a common cause.

Common situations: Floating-point division results used as indices, averages or ratios passed as positions, or parsed floats not rounded.

Related errors


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