eslint/no-constant-binary-expression 正確性
作用
禁止運算結果不影響值的表達式
為何這是不好的?
總是評估為 true 或 false 的比較,以及總是短路或從不短路的邏輯表達式 (||
, &&
, ??
) 都很可能是程式設計師錯誤的跡象。
這些錯誤在運算子優先順序很容易判斷錯誤的複雜表達式中尤其常見。
此外,此規則會偵測與新建立的物件/陣列/函數等的比較。在 JavaScript 中,物件是透過引用進行比較,新建立的物件永遠不能與任何其他值 ===
。對於來自物件透過值進行比較的語言的程式設計師來說,這可能會令人感到驚訝。
範例
javascript
// 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.
// 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`.