JS Refactoring Combo: Simplify If-Else Variable Initialization
Lars Grammel

Lars Grammel @lgrammel

About: AI Engineering consulting & contract work. Building the ModelFusion AI library for TypeScript.

Joined:
Dec 9, 2020

JS Refactoring Combo: Simplify If-Else Variable Initialization

Publish Date: Apr 27 '22
10 1

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);
}
Enter fullscreen mode Exit fullscreen mode

Refactoring Steps

Refactor initializing a variable in an if-else statement

💡  The refactoring steps are using P42 JavaScript Assistant v1.99.

  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);
Enter fullscreen mode Exit fullscreen mode

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.

Comments 1 total

  • Muhammad Harith Zainudin
    Muhammad Harith ZainudinApr 28, 2022

    This is good! Sometimes we don't realise that our code can be shortened. Will surely try to install p42 after this!

Add comment