
no-constant-binary-expression
不允許運算不會影響值的運算式
✅ 建議
在設定檔中使用來自 @eslint/js
的 recommended
設定會啟用此規則
總是評估為 true 或 false 的比較,以及總是短路或永不短路的邏輯運算式 (||
、&&
、??
) 都很可能是程式設計師錯誤的跡象。
這些錯誤在運算子優先順序容易誤判的複雜運算式中尤其常見。例如
// One might think this would evaluate as `a + (b ?? c)`:
const x = a + b ?? c;
// But it actually evaluates as `(a + b) ?? c`. Since `a + b` can never be null,
// the `?? c` has no effect.
此外,此規則會偵測與新建立的物件/陣列/函式等的比較。在 JavaScript 中,物件是透過參考進行比較的,新建立的物件永遠不可能 ===
任何其他值。對於來自物件是透過值進行比較的語言的程式設計師來說,這可能會令人驚訝。
// Programmers coming from a language where objects are compared by value might expect this to work:
const isEmpty = x === [];
// However, this will always result in `isEmpty` being `false`.
規則詳細資訊
此規則識別 ==
和 ===
比較,根據 JavaScript 語言的語意,這些比較將始終評估為 true
或 false
。
它還識別 ||
、&&
和 ??
邏輯運算式,這些運算式將始終或永不短路。
此規則的錯誤程式碼範例
在遊樂場中開啟
/*eslint no-constant-binary-expression: "error"*/
const value1 = == null;
const value2 = condition ? x : || DEFAULT;
const value3 = == null;
const value4 = === true;
const objIsEmpty = someObj === ;
const arrIsEmpty = someArr === ;
const shortCircuit1 = && condition2;
const shortCircuit2 = || condition2;
const shortCircuit3 = ?? condition2;
此規則的正確程式碼範例
在遊樂場中開啟
/*eslint no-constant-binary-expression: "error"*/
const value1 = x == null;
const value2 = (condition ? x : {}) || DEFAULT;
const value3 = !(foo == null);
const value4 = Boolean(foo) === true;
const objIsEmpty = Object.keys(someObj).length === 0;
const arrIsEmpty = someArr.length === 0;
相關規則
版本
此規則在 ESLint v8.14.0 中引入。
延伸閱讀
