Remove unnecessary conditional expression

Replace a conditional expression with its condition or its result.

Remove unnecessary conditional expression

The "Remove unnecessary conditional expression" refactoring replaces a conditional expression (ternary) in two situations:

  1. When the ternary returns true when truthy and false when falsy.

    aCondition ? true : false
    // changes into:
    aCondition
  2. 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

Learn More

Available In