sindresorhus/eslint-plugin-unicorn

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

Open

#2,772 opened on 2025年10月7日

GitHub で見る
 (10 comments) (6 reactions) (0 assignees)JavaScript (5,022 stars) (468 forks)user submission
help wantednew rule

説明

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.

コントリビューターガイド