If-statements are often used to initialize variables with different values depending on a condition. This 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
💡 The refactoring steps are using P42 JavaScript Assistant v1.99.
- Convert the if-else statement into a conditional expression
- Merge variable declaration and initialization
- 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
.
Top comments (1)
This is good! Sometimes we don't realise that our code can be shortened. Will surely try to install p42 after this!