Simplify if-else variable initialization

Convert a conditional variable initialization with if-else to a conditional expression.

Simplify if-else variable initialization

If-statements are sometimes used to initialize variables with different values depending on a condition. This usage of if-statements can lead to unnecessary code duplication and can often be shortened with the conditional operator.

Before (Example)

let movedObject;
if (direction === "left") {
  movedObject = moveLeft(original);
} else {
  movedObject = moveRight(original);
}

Refactoring Steps

  1. Convert the if-else statement into a conditional expression
  2. Merge variable declaration and initialization
  3. Convert let to const

After (Example)

const movedObject = direction === "left"
  ? moveLeft(original)
  : moveRight(original);

The change to const is only possible if the variable is not re-assigned later. It has the advantage that it communicates the immutability of movedObject.

Learn More