New rule: no mixed logical operators
See original GitHub issueI’m proposing a rule that warns when logical operators like &&
and ||
are mixed. The purpose is to avoid errors like the one fixed here:
if (a && a.b === 1 || a.b === 2) {
}
In this example, we are mixing &&
and ||
. We are probably expecting not to enter inside the if
block if
a
is falsya.b
is neither1
nor2
but what the actual operation will be is (a && a.b === 1) || a.b === 2
. Meaning, if a
is undefined
, then we will be evaluating a.b === 2
, which will create an error.
If we had wrapped our different conditions in parentheses a && (a.b === 1 || a.b === 2)
, then this would have resulted in the wanted behavior.
Fail
if (a && a.b === 1 || a.b === 2) {
}
a && b || c
a || b && c
Pass
a && b && c
a || b || c
a && (b || c)
a || (b && c)
I think the rule is pretty generic and can help avoid “easy” mistakes, and therefore has it’s place in ESLint. I don’t mind adding it to a custom plugin otherwise. I’d be happy to write the rule 😃
Issue Analytics
- State:
- Created 7 years ago
- Reactions:4
- Comments:39 (39 by maintainers)
Top Results From Across the Web
no-mixed-operators - ESLint - Pluggable JavaScript Linter
This rule warns when different operators are used consecutively without parentheses in an expression.
Read more >Compound Booleans with logical operators - Khan Academy
Since that expression is made entirely of OR operators, the expression is true as long as any of the conditions are true. It...
Read more >AND and OR logical operators - IBM
Logical operators combine relations according to the following rules: The ampersand (&) symbol is a valid substitute for the logical operator AND ....
Read more >Using logical operator between mixed data (include out of ...
1. & and | are bitwise operators, not logical operators. – Barmar · 1. See short circuiting · 3. Saving literally two characters...
Read more >Operator precedence - JavaScript - MDN Web Docs - Mozilla
A always produces a boolean, not a constructor function.) For postfix unary operators (namely, ++ and -- ), the same rules apply.
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@nzakas Yes, my concern was that this rule only applied to logical operators. Now that it has been re-envisioned to lint all binary operators, it’s fine.