Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 27, 2022 09:25 am GMT

JavaScript Refactoring Combo: Convert conditional initialization with if-else into conditional expression

This post is about combining refactorings with the P42 JavaScript Assistant v1.99.

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

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

After

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.

Refactoring Steps

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

Refactoring Example

Refactor initializing a variable in an if-else statement


Original Link: https://dev.to/lgrammel/javascript-refactoring-combos-convert-conditional-initialization-with-if-else-into-conditional-expression-5g5j

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To