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
true
when truthy andfalse
when falsy.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 Boolean(aCondition)
.
Removes conditions with side-effects
The condition of a ternary expression obj.method() ? value : value
could have side effects. When replacing the ternary with value
, 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 value
:
const aVariable = obj.method() ? value : value;
// becomes
obj.method();
const aVariable = value;
Configuration
- Code Assist ID (for the configuration file):
remove-unnecessary-conditional-expression
- You can configure custom keyboard shortcuts with this code action kind:
refactor.p42.remove-unnecessary-conditional-expression
- This code assist provides refactoring suggestions. Learn how to configure the refactoring suggestion visibility.