TheAlgorithms/JavaScript · error · TypeError

Index cannot be Negative

Error message

Index cannot be Negative

What it means

The lucas function returns the nth Lucas number using an iterative loop. A negative index has no valid output in this implementation, so the guard at line 18 rejects index < 0 with a TypeError. This check fires before the decimal check.

Source

Thrown at Maths/LucasSeries.js:18

/*
  Program to get the Nth Lucas Number
  Article on Lucas Number: https://en.wikipedia.org/wiki/Lucas_number
  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 a non-negative integer index.
  2. Clamp the index to a minimum of 0 before calling.
  3. Check that index >= 0 in the calling code before invoking.

Example fix

// before
lucas(pos - 1) // throws when pos === 0
// after
if (pos < 1) throw new RangeError('pos must be >= 1')
lucas(pos - 1)
Defensive patterns

Strategy: validation

Validate before calling

if (typeof index !== 'number' || index < 0) {
  throw new RangeError('index must be a non-negative number')
}
lucas(index)

Type guard

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

Prevention

When it happens

Trigger: Calling lucas(-1) or lucas(-5). Any negative value triggers this error. A computed index that goes negative (e.g., pos - 1 when pos is 0) is a common source.

Common situations: Off-by-one subtraction where index becomes negative, array reversal indexing, negative results from modulo operations on negative numbers.

Related errors


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