An Interest In:
Web News this Week
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
April 27, 2022 09:25 am GMT
Original Link: https://dev.to/lgrammel/javascript-refactoring-combos-convert-conditional-initialization-with-if-else-into-conditional-expression-5g5j
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
- Convert the if-else statement into a conditional expression
- Merge variable declaration and initialization
- Convert let to const
Refactoring Example
Original Link: https://dev.to/lgrammel/javascript-refactoring-combos-convert-conditional-initialization-with-if-else-into-conditional-expression-5g5j
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To