Remove unnecessary conditional expression
Replace a conditional expression with its condition or its result.
The "Remove unnecessary conditional expression" refactoring replaces a conditional expression (ternary) in two situations:
When the ternary returns
truewhen truthy and
aCondition ? true : false // changes into: aCondition
When the ternary returns the same value, regardless of whether the condition is truthy or falsy:
aCondition ? aValue : aValue // changes into: aValue
Why is this refactoring helpful?
Unnecessary conditional expressions can increase the complexity and obfuscate the behavior of the code. Removing them increases the readability and makes the code more straightforward.
What do I need to consider?
Removes conversion to boolean
With an expression
aCondition ? true : false, the result always has the primitive type boolean. However, the input
aCondition could have any type, even if the truthiness is the same.
When conversion to boolean is needed, a more straightforward way for converting a value to boolean is
Removes conditions with side-effects
The condition of a ternary expression
obj.method() ? value : value could have side effects. When replacing the ternary with
obj.method() is not executed any more. This change could impact the program behavior.
In such cases, clearer alternative is to call
obj.method() beforehand, and then use
const aVariable = obj.method() ? value : value; // becomes obj.method(); const aVariable = value;