diff --git a/lib/rules/no-constant-condition.js b/lib/rules/no-constant-condition.js index 39c2928eed3..fb36207ebbb 100644 --- a/lib/rules/no-constant-condition.js +++ b/lib/rules/no-constant-condition.js @@ -5,6 +5,13 @@ "use strict"; +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const EQUALITY_OPERATORS = ["===", "!==", "==", "!="]; +const RELATIONAL_OPERATORS = [">", "<", ">=", "<=", "in", "instanceof"]; + //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ @@ -110,7 +117,18 @@ module.exports = { const isRightShortCircuit = (isRightConstant && isLogicalIdentity(node.right, node.operator)); return (isLeftConstant && isRightConstant) || - (node.operator === "||" && isRightConstant && node.right.value) || // in the case of an "OR", we need to know if the right constant value is truthy + ( + + // in the case of an "OR", we need to know if the right constant value is truthy + node.operator === "||" && + isRightConstant && + node.right.value && + ( + !node.parent || + node.parent.type !== "BinaryExpression" || + !(EQUALITY_OPERATORS.includes(node.parent.operator) || RELATIONAL_OPERATORS.includes(node.parent.operator)) + ) + ) || isLeftShortCircuit || isRightShortCircuit; } diff --git a/tests/lib/rules/no-constant-condition.js b/tests/lib/rules/no-constant-condition.js index c89f9080d6e..e27e3b390b7 100644 --- a/tests/lib/rules/no-constant-condition.js +++ b/tests/lib/rules/no-constant-condition.js @@ -61,6 +61,18 @@ ruleTester.run("no-constant-condition", rule, { "if(a && 'str'){}", "if('str' || abc==='str'){}", + // #11306 + "if ((foo || 'bar') === 'baz') {}", + "if ((foo || 'bar') !== 'baz') {}", + "if ((foo || 'bar') == 'baz') {}", + "if ((foo || 'bar') != 'baz') {}", + "if ((foo || 233) > 666) {}", + "if ((foo || 233) < 666) {}", + "if ((foo || 233) >= 666) {}", + "if ((foo || 233) <= 666) {}", + "if ((key || 'k') in obj) {}", + "if ((foo || {}) instanceof obj) {}", + // { checkLoops: false } { code: "while(true);", options: [{ checkLoops: false }] }, { code: "for(;true;);", options: [{ checkLoops: false }] },