sindresorhus/eslint-plugin-unicorn

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

已關閉

#2,772 建立於 2025年10月7日

 (10 則留言) (7 個反應) (0 位負責人)JavaScript (468 個分叉)user submission
help wantednew rule

倉庫指標

星標
 (5,022 顆星)
PR 合併指標
 (平均合併 4小時 30分鐘) (30 天內合併 26 個 PR)

描述

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.

貢獻者指南