oxc-project/oxc · error · OxcDiagnostic

Prefer `includes()` over `indexOf()` when checking for exist

Error message

Prefer `includes()` over `indexOf()` when checking for existence or non-existence.

What it means

Diagnostic from the unicorn/prefer-includes lint rule. It fires when `indexOf()` (or `lastIndexOf()`) is compared against -1 or 0 in a boolean context (e.g. `arr.indexOf(x) !== -1`) to test membership; `includes()` expresses the same check directly and is less error-prone. The flagged input is the binary/comparison expression wrapping the `indexOf` call. It is a lint suggestion, not a runtime error.

Source

Thrown at crates/oxc_linter/src/rules/unicorn/prefer_includes.rs:18

use oxc_ast::{
    AstKind,
    ast::{ChainElement, Expression},
};
use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::{GetSpan, Span};
use oxc_syntax::operator::{BinaryOperator, UnaryOperator};

use crate::{
    AstNode,
    ast_util::{call_expr_method_callee_info, is_method_call},
    context::LintContext,
    rule::Rule,
};

fn prefer_includes_diagnostic(span: Span) -> OxcDiagnostic {
    OxcDiagnostic::warn(
        "Prefer `includes()` over `indexOf()` when checking for existence or non-existence.",
    )
    .with_label(span)
}

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

#[derive(Debug, Clone, Copy)]
enum ComparisonKind {
    // `indexOf(...) != -1` / `!== -1`
    ExistsOrUndefined,
    // `indexOf(...) > -1` / `>= 0`
    ExistsOnly,
    // `indexOf(...) == -1` / `=== -1` / `< 0`
    NotExistsOnly,
}

View on GitHub (pinned to e1e7af627c)

Solutions

  1. Replace `x.indexOf(v) !== -1` with `x.includes(v)`
  2. Replace `x.indexOf(v) === -1` with `!x.includes(v)`
  3. Keep `indexOf()` only when the actual index position is needed
  4. Apply the rule's auto-fix
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at crates/oxc_linter/src/rules/unicorn/prefer_includes.rs:18 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/df9cac5159397b13. Report an issue: GitHub.