
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
的 ==
和 ===
比较。
它还识别将总是或从不短路的 ||
、&&
和 ??
逻辑表达式。
此规则的错误代码示例
在 Playground 中打开
/*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;
此规则的正确代码示例
在 Playground 中打开
/*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 中引入。
延伸阅读
