oxc-project/oxc · error · OxcDiagnostic
Do not use `Array#forEach`
Error message
Do not use `Array#forEach`
What it means
Raised by unicorn/no-array-for-each when `Array#forEach` is used. The rule inspects the callback's parameter shape (element-only vs index-using) during run() and selects tailored advice; the faulting input is the `.forEach(...)` call at the labeled span.
Source
Thrown at crates/oxc_linter/src/rules/unicorn/no_array_for_each.rs:33
};
fn no_array_for_each_diagnostic(
span: Span,
callback_arguments: CallbackArguments,
) -> OxcDiagnostic {
let help = match callback_arguments {
CallbackArguments::ElementOnly => {
"Replace it with a `for…of` loop. It is faster, more readable, and allows early exits with `break` or `return`."
}
CallbackArguments::Index => {
"For arrays that need the index, replace it with a `for…of` loop over `.entries()`, such as `for (const [index, element] of array.entries())`. Otherwise, use the appropriate `for…of` loop. Array `.entries()` keeps indexes numeric and loops allow early exits with `break` or `return`."
}
CallbackArguments::Extra => {
"Replace it with a `for…of` loop that preserves the extra callback arguments you use. For arrays, `.entries()` provides the numeric index, and the original array can be referenced directly if needed."
}
};
OxcDiagnostic::warn("Do not use `Array#forEach`").with_help(help).with_label(span)
}
#[derive(Debug, Default, Clone)]
pub struct NoArrayForEach;
declare_oxc_lint!(
/// ### What it does
///
/// Forbids the use of `Array#forEach` in favor of a for loop.
///
/// ### Why is this bad?
///
/// Benefits of [`for…of` statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) over the `forEach` method can include:
///
/// - Faster
/// - Better readability
/// - Ability to exit early with `break` or `return`
///View on GitHub (pinned to e1e7af627c)
Solutions
- Replace with a `for…of` loop, which is faster and supports `break`/`return` early exits
- When the index is needed, iterate `for (const [index, element] of array.entries())`
- For pure transformations, prefer `map`, `filter`, or `reduce` to express intent
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at crates/oxc_linter/src/rules/unicorn/no_array_for_each.rs:33 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/034b561a8b04bb01.
Report an issue: GitHub.