{"record":{"id":"a117c6f3b8dd98f0","repo":"TheAlgorithms/JavaScript","slug":"index-cannot-be-negative","errorCode":null,"errorMessage":"Index cannot be Negative","messagePattern":"Index cannot be Negative","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"Maths/LucasSeries.js","lineNumber":18,"sourceCode":"/*\n  Program to get the Nth Lucas Number\n  Article on Lucas Number: https://en.wikipedia.org/wiki/Lucas_number\n  Examples:\n    > loopLucas(1)\n    1\n    > loopLucas(20)\n    15127\n    > loopLucas(100)\n    792070839848372100000\n*/\n\n/**\n * @param {Number} index The position of the number you want to get from the Lucas Series\n */\nfunction lucas(index) {\n  // index can't be negative\n  if (index < 0) throw new TypeError('Index cannot be Negative')\n\n  // index can't be a decimal\n  if (Math.floor(index) !== index)\n    throw new TypeError('Index cannot be a Decimal')\n\n  let a = 2\n  let b = 1\n  for (let i = 0; i < index; i++) {\n    const temp = a + b\n    a = b\n    b = temp\n  }\n  return a\n}\n\nexport { lucas }\n","sourceCodeStart":1,"sourceCodeEnd":35,"githubUrl":"https://github.com/TheAlgorithms/JavaScript/blob/5c39e87a9a31f279c60f830ad74a845e4788a517/Maths/LucasSeries.js#L1-L35","documentation":"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.","triggerScenarios":"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.","commonSituations":"Off-by-one subtraction where index becomes negative, array reversal indexing, negative results from modulo operations on negative numbers.","solutions":["Pass a non-negative integer index.","Clamp the index to a minimum of 0 before calling.","Check that index >= 0 in the calling code before invoking."],"exampleFix":"// before\nlucas(pos - 1) // throws when pos === 0\n// after\nif (pos < 1) throw new RangeError('pos must be >= 1')\nlucas(pos - 1)","handlingStrategy":"validation","validationCode":"if (typeof index !== 'number' || index < 0) {\n  throw new RangeError('index must be a non-negative number')\n}\nlucas(index)","typeGuard":"const isNonNegativeIndex = (i) => typeof i === 'number' && Number.isInteger(i) && i >= 0","tryCatchPattern":null,"preventionTips":["Clamp sequence indices to >= 0 before calling.","Check subtraction results before using them as indices.","Guard against negative results from modulo operations on negative numbers."],"tags":["math","precondition","index-validation","sequence"],"backgroundTag":null,"analyzedSha":"5c39e87a9a31f279c60f830ad74a845e4788a517","analyzedAt":"2026-08-13T04:54:54.474Z","schemaVersion":2},"datasetVersion":"2026-08-13T09:17:06.757Z"}