oxc-project/oxc · warning · OxcDiagnostic

Unexpected `if` as the only statement in an `else` block

Error message

Unexpected `if` as the only statement in an `else` block

What it means

Diagnostic from oxlint's eslint/no-lonely-if rule (crates/oxc_linter/src/rules/eslint/no_lonely_if.rs:10). It reports an if statement that is the only statement inside an else block: 'if (a) {...} else { if (b) {...} }'. The idiomatic form is 'else if', which avoids the extra indentation and brace level. The label is placed on the span of the lonely if keyword.

Source

Thrown at crates/oxc_linter/src/rules/eslint/no_lonely_if.rs:10

use crate::{AstNode, context::LintContext, rule::Rule};
use oxc_ast::AstKind;
use oxc_ast::ast::{IfStatement, Statement};
use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::Span;

fn no_lonely_if_diagnostic(lonely_if: &IfStatement) -> OxcDiagnostic {
    let span = Span::sized(lonely_if.span.start, 2);
    OxcDiagnostic::warn("Unexpected `if` as the only statement in an `else` block")
        .with_help("Consider using `else if` instead.")
        .with_label(span)
}

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

declare_oxc_lint!(
    /// ### What it does
    ///
    /// Disallow `if` statements as the only statement in `else` blocks.
    ///
    /// ### Why is this bad?
    ///
    /// When an `if` statement is the only statement in an `else` block, it is often clearer to use
    /// an `else if` instead.
    ///
    /// ### Examples

View on GitHub (pinned to e1e7af627c)

Solutions

  1. Merge into an else-if chain: 'if (a) {...} else if (b) {...}'
  2. If the nested if has its own else, flatten the whole chain with else-if at each level
  3. When the chain grows long, consider a lookup table, switch, or early-return guard clauses instead

Example fix

// before
if (a) {
  doA();
} else {
  if (b) {
    doB();
  }
}

// after
if (a) {
  doA();
} else if (b) {
  doB();
}
Defensive patterns

Strategy: validation

Prevention

When it happens

Trigger: An else clause whose block contains exactly one statement and that statement is an if (with or without its own else chain); commonly produced when adding a new condition to an existing if/else by hand.

Common situations: Incrementally grown conditionals during bug fixes; code formatted with the else block always braced; developers unaware that 'else if' is just else followed by an if statement.

Related errors


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