no-constant-binary-expression
禁止操作不影响值的表达式
在 配置文件 中使用来自 @eslint/js 的 recommended 配置可以启用此规则
总是评估为真或假的比较,以及总是短路或从不短路的逻辑表达式(||、&&、??)都可能是程序员错误的迹象。
🌐 Comparisons which will always evaluate to true or false and logical expressions (||, &&, ??) which either always short-circuit or never short-circuit are both likely indications of programmer error.
这些错误在运算符优先级容易判断错误的复杂表达式中尤其常见。例如:
🌐 These errors are especially common in complex expressions where operator precedence is easy to misjudge. For example:
// 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 中,对象是按引用比较的,新的构造对象 永远 不可能 === 任何其他值。这对于来自按值比较对象的语言的程序员来说可能会让人感到惊讶。
🌐 Additionally, this rule detects comparisons to newly constructed objects/arrays/functions/etc. In JavaScript, where objects are compared by reference, a newly constructed object can never === any other value. This can be surprising for programmers coming from languages where objects are compared by value.
// 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`.
规则详情
🌐 Rule Details
该规则识别 == 和 === 的比较,根据 JavaScript 语言的语义,这些比较将始终评估为 true 或 false。
🌐 This rule identifies == and === comparisons which, based on the semantics of the JavaScript language, will always evaluate to true or false.
它还识别出 ||、&& 和 ?? 逻辑表达式,这些表达式要么总是短路,要么从不短路。
🌐 It also identifies ||, && and ?? logical expressions which will either always or never short-circuit.
此规则的错误代码示例:
🌐 Examples of incorrect code for this rule:
/*eslint no-constant-binary-expression: "error"*/
const value1 = +x == null;
const value2 = condition ? x : {} || DEFAULT;
const value3 = !foo == null;
const value4 = new Boolean(foo) === true;
const objIsEmpty = someObj === {};
const arrIsEmpty = someArr === [];
const shortCircuit1 = condition1 && false && condition2;
const shortCircuit2 = condition1 || true || condition2;
const shortCircuit3 = condition1 ?? "non-nullish" ?? condition2;
符合此规则的正确代码示例:
🌐 Examples of correct code for this rule:
/*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;
选项
🌐 Options
此规则没有选项。
🌐 This rule has no options.
相关规则
版本
此规则是在 ESLint v8.14.0 中引入。