Swap the left and right operands and update the operator if necessary.
The flip operator refactoring exchanges a binary expression's left and right operand. When necessary, it updates the operator, e.g., when changing from
a < b to
b > a.
Why is this refactoring helpful?
Flipping operators can improve the readability of the code
For example, there might be several expressions with similar components which are ordered differently:
const a = f(value1) && g(); const b = h() && f(value1);
&& in the second statement can help see the duplication of
const a = f(value1) && g(); const b = f(value1) && h();
Flipping operators can be used to evaluate less expensive operations first when short-circuiting
This can help avoid heavy computations:
const isOk = heavyComputation() && flag;
is flipped to
const isOk = flag && heavyComputation();
What do I need to consider?
Flipping operators can change the result value of short-circuiting operations
The resulting value can change when the operator is
||. The falsy/truthy state of the resulting value will be the same as before, so flipping the operator is often safe in conditions but unsafe in assignments and expressions.
Flipping operators changes the evaluation order
When there are side-effects on both sides of the expression, the order of their execution changes, leading to different behavior. When the operator is a short-circuiting operator, and there is a side effect on any side of the expression, it may not be invoked in the same cases after flipping.
+ operator changes the result of the string concatenation operation.
- Code Assist ID (for the configuration file):
- You can configure custom keyboard shortcuts with this code action kind: