Move duplicated first statement out of if-else
Move a first statement that appears in both the if and the else block out of the if-else statement.

Why is this useful?
Moving duplicated statements out of an if-else removes code duplication and clarifies that their execution is not dependent on the condition of the if statement.
Mechanics
If the first statement is the same in the if-block and the else-block of an if-statement, then the statement can be pulled out. and moved above the if-statement.
What do I need to consider?
There are several scenarios in which moving a duplicated statement out of an if-else statement can lead to a change of behavior:
- When lifting out a first statement that impacts the evaluation of the if-condition, the if-else might behave differently after the refactoring.
For example,
printslet a = 2; if (a === 2) { a = 3; console.log("if"); } else { a = 3; console.log("else"); }
"if"
before the refactoring and"else"
afterward. When lifting out a first statement, when the if-condition has side-effects, the statement might behave differently than before. For example,
let a = "before"; const f = () => { console.log(a); return true; }; if (f()) { a = "after"; somethingElse1(); } else { a = "after"; somethingElse2(); }
prints
"before"
before the refactoring and"after"
afterward.
P42 provides safety information when any one of the scenarios is possible.
Configuration
- This code assist provides refactoring suggestions. Learn how to configure the refactoring suggestion visibility.