The logical NOT (
!) operator takes truth to falsity and vice versa.(c) MDN
🐊Putout plugin adds ability to simplify logical expressions containing
comparisons which will always evaluate to true or false since it's likely indications of programmer error.
Complements @putout/plugin-apply-comparison-order.
npm i @putout/plugin-logical-expressions -D
- ✅ apply-destructuring;
- ✅ convert-bitwise-to-logical;
- ✅ convert-coalescing-to-logical;
- ✅ remove-boolean;
- ✅ remove-duplicates;
- ✅ remove-useless-coalescing;
- ✅ simplify;
{
"rules": {
"logical-expressions/apply-destructuring": "on",
"logical-expressions/convert-bitwise-to-logical": "on",
"logical-expressions/convert-coalescing-to-logical": "on",
"logical-expressions/remove-boolean": "on",
"logical-expressions/remove-duplicates": "on",
"logical-expressions/remove-useless-coalescing": "on",
"logical-expressions/simplify": "on"
}
}Checkout in 🐊Putout Editor.
const arrow = (el) => el().text && el().text.trim();
const value = getState().workbench && getState().workbench.code;const arrow = (el) => {
const {text} = el();
return text && text.trim();
};
const {workbench} = getState();
const value = workbench && workbench.code;The bitwise OR operator (
|) returns a1in each bit position for which the corresponding bits of either or both operands are1s.The operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones).
(c) MDN
Convert bitwise to logical operator, when one of operands is not a number, since mostly likely it is an error.
a | !b;
if (!(a !== b))
fn();a || !b;
if (a === b)
fn();Checkout in 🐊Putout Editor.
const fn = cb ?? noop;const fn = cb || noop;A boolean is a logical data type that can have only the values
trueorfalse.(c) MDN
const t = true && false;const t = false;| Linter | Rule | Fix |
|---|---|---|
| 🐊 Putout | logical-expressions |
✅ |
| ⏣ ESLint | no-constant-binary-expression |
❌ |
const t = a && b && a;const t = a && b;Checkout in 🐊Putout Editor.
a ?? undefined;a;const is = !(options && !options.bidirectional);
if (!left.type === 'UnaryExpression') {}
const oneOf = a || a;
const same = a === a;
a() && b;const is = !options || options.bidirectional;
if (!isUnaryExpression(left)) {}
const oneOf = a;
const same = true;
a();The rule also simplify duplication use:
-if (a && b || a && c) {
+if (a && (b || c)) {
}Wrong cases with instanceof:
-!a instanceof b;
-a instanceof !b;
-!a instanceof !b;
+!(a instanceof b);Wrong cases with in:
-!a in b;
-a in !b;
+!(a in b);In case of duplicates:
-a && b && a
+a && bMIT