oxc-project/oxc · error · OxcDiagnostic

Prefer negative index over `.length - index` when possible.

Error message

Prefer negative index over `.length - index` when possible.

What it means

Diagnostic from the unicorn/prefer-negative-index lint rule. It fires when an expression of the form `array.length - n` is used as an index (in member access, `at()`, `splice`, `slice`, or method arguments) and `n` is a positive number or the same array variable; a negative index (`array.at(-1)`, `arr[arr.length - 1]` -> `arr.at(-1)`) is the idiomatic, shorter form supported by modern methods. It is a lint suggestion, not a runtime error.

Source

Thrown at crates/oxc_linter/src/rules/unicorn/prefer_negative_index.rs:15

use oxc_ast::{
    AstKind,
    ast::{
        Argument, ArrayExpressionElement, BinaryExpression, BinaryOperator, Expression,
        StaticMemberExpression,
    },
};
use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::{GetSpan, Span};

use crate::{AstNode, context::LintContext, fixer::Fix, rule::Rule, utils::is_same_expression};

fn prefer_negative_index_diagnostic(span: Span) -> OxcDiagnostic {
    OxcDiagnostic::warn("Prefer negative index over `.length - index` when possible.")
        .with_label(span)
}

#[derive(Debug, Default, Clone)]
pub struct PreferNegativeIndex;

#[derive(Debug)]
enum TypeOptions {
    String,
    Array,
    TypedArray,
    Literal,
    Unknown,
}

declare_oxc_lint!(
    /// ### What it does
    ///

View on GitHub (pinned to e1e7af627c)

Solutions

  1. Replace `arr[arr.length - 1]` with `arr.at(-1)`
  2. Replace `arr.length - n` arguments to `at`/`slice`/`splice` with `-n`
  3. Apply the rule's auto-fix
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at crates/oxc_linter/src/rules/unicorn/prefer_negative_index.rs:15 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of oxc-project/oxc@e1e7af627c (2026-08-20). Data as JSON: /api/errors/fa90a52a673f8e1f. Report an issue: GitHub.