{"record":{"id":"18308340568472a6","repo":"oxc-project/oxc","slug":"avoid-using-length-as-the-index-in-array-with","errorCode":null,"errorMessage":"Avoid using `.length` as the index in `Array#with()`.","messagePattern":"Avoid using `\\.length` as the index in `Array#with\\(\\)`\\.","errorType":"validation","errorClass":"OxcDiagnostic","httpStatus":null,"severity":"error","filePath":"crates/oxc_linter/src/rules/unicorn/no_confusing_array_with.rs","lineNumber":21,"sourceCode":"    ast::{Expression, UnaryOperator},\n};\nuse oxc_diagnostics::OxcDiagnostic;\nuse oxc_macros::declare_oxc_lint;\nuse oxc_span::Span;\n\nuse crate::{\n    AstNode, ast_util::is_method_call, context::LintContext, rule::Rule, utils::is_same_expression,\n};\n\nfn negative_index_diagnostic(span: Span) -> OxcDiagnostic {\n    OxcDiagnostic::warn(\"Avoid using a negative index with `Array#with()`.\")\n        .with_note(\"`Array#with()` interprets a negative index as an offset from the end.\")\n        .with_help(\"Use a non-negative index to make the intended position explicit.\")\n        .with_label(span)\n}\n\nfn length_index_diagnostic(span: Span) -> OxcDiagnostic {\n    OxcDiagnostic::warn(\"Avoid using `.length` as the index in `Array#with()`.\")\n        .with_note(\"An array's `.length` is one past its last valid index.\")\n        .with_help(\"Use `.length - 1` to replace the last element.\")\n        .with_label(span)\n}\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\nenum ConfusingWithIndex {\n    Negative,\n    Length,\n}\n\n#[derive(Debug, Default, Clone)]\npub struct NoConfusingArrayWith;\n\ndeclare_oxc_lint!(\n    /// ### What it does\n    ///\n    /// Disallows confusing uses of [`Array#with()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/with).","sourceCodeStart":3,"sourceCodeEnd":39,"githubUrl":"https://github.com/oxc-project/oxc/blob/e1e7af627c8843ab64044ed466b128fcc21a035b/crates/oxc_linter/src/rules/unicorn/no_confusing_array_with.rs#L3-L39","documentation":"Diagnostic from the oxlint rule `unicorn/no-confusing-array-with` (length-index arm, category: suspicious). Valid `.with()` indexes are `0..length-1`; `.with()` replaces an element and cannot append, so passing `arr.length` (one past the last valid index) always throws a RangeError at runtime. The rule catches this statically whenever the index is a `.length` member access on an expression provably identical to the call receiver, converting a guaranteed crash into a lint-time error.","triggerScenarios":"`array.with(array.length, value)` (with any number of extra arguments), `object.items.with(object.items.length, value)` — the index is a static `.length` property whose object is the same expression as the receiver. `otherArray.length` or `array.length - 1` passes.","commonSituations":"Assuming `.with()` can grow the array, mirroring the `arr[arr.length] = v` mutation idiom; immutable-state code (React/Redux) rewriting elements; first contact with ES2023 change-by-copy methods.","solutions":["To append immutably, use spread: `const next = [...items, item]`","To replace the last element, use `items.with(items.length - 1, item)`","If the index is computed at runtime, validate it first: `if (!Number.isInteger(i) || i < 0 || i >= arr.length) throw new RangeError(...)`"],"exampleFix":"// before (always throws RangeError)\nconst next = items.with(items.length, 'new');\n\n// after\nconst next = [...items, 'new'];","handlingStrategy":"validation","validationCode":"function safeWith(arr, index, value) {\n  if (!Number.isInteger(index) || index < 0 || index >= arr.length) {\n    throw new RangeError(`index ${index} out of range 0..${arr.length - 1}`);\n  }\n  return arr.with(index, value);\n}","typeGuard":null,"tryCatchPattern":"try {\n  arr.with(idx, value);\n} catch (err) {\n  if (err instanceof RangeError) {\n    // report invalid index instead of crashing\n  }\n  throw err;\n}","preventionTips":["Remember `.with()` is replace-only (0..length-1); use spread to append","Bound-check computed indexes before calling `.with()`","Keep this rule at error level in CI — it reports guaranteed crashes"],"tags":["arrays","es2023","runtime-error","bug","oxlint"],"backgroundTag":"array-index-out-of-bounds","analyzedSha":"e1e7af627c8843ab64044ed466b128fcc21a035b","analyzedAt":"2026-08-20T07:01:07.079Z","contentChangedAt":"2026-08-20T07:01:07.079Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}