Skip to content

Rule proposal: forbid declarations that are not used before an early return #2772

@joaocraveiro

Description

@joaocraveiro

Description

Flag variables that are declared before a possible early exit (return, throw, break, continue) but are only used after that exit point. Such variables may be unnecessary in the early-exit path and can be safely moved down to reduce scope and avoid unneeded initialisation.

Examples

// ❌
function foo(bar) {
  const res = getRes();
  if (!bar) return;
  console.log(res);
}

// ✅
function foo(bar) {
  if (!bar) return;
  const res = getRes();
  console.log(res);
}

Proposed rule name

no-unused-vars-before-exit

Additional Info

Introducing this rule promotes clearer, more efficient control flow by encouraging developers to declare variables only when they are truly needed. In functions or loops that contain early exits (like return, throw, break, or continue), variables declared before these exit points but used only afterwards are unnecessary in those paths. By delaying such declarations, developers can avoid performing unneeded work—especially when it involves expensive operations or function calls.

This rule also helps minimise variable scope, making code easier to read and reason about. Keeping variables close to where they are used aligns with modern JavaScript practices and complements existing rules like no-unused-vars and prefer-const. Overall, it encourages a more intentional structure, better performance in early-exit scenarios, and improved code maintainability.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions