no-constant-binary-expression
禁止操作不影响值的表达式
将始终评估为真或假的比较以及始终短路或从不短路的逻辑表达式(||
,&&
,??
)都可能表明程序员错误。
这些错误在运算符优先级容易误判的复杂表达式中尤为常见。例如:
// 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
。
d+9bWnXMFCRstZsLl5aP8smq8ahelGMEMRA9120HdoLgrDz+63/FrmDvZmjhCdyILWg9v19e7OqpizHWGi8RnACFLZIBOla6i00kN9KMwDQAUDDYFHbLZ1YdY8UPCU7lO9mo0CvvkTXT4JG/erLV2BTK4X2o5O8gz3gEbc5zKIk=
RcKra7ltwcYILSI938QSHqeDUJNF18dCoW/jnWHvHMqaGbJjs/cbfGmCaTTyoOih
/*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;
HuZdr89SsSFFHS0WvJtjpxEp0Co9MKRIcy8aDCD9kElD4NuTDQ+687mcbM02zKTG
/*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;