DEV Community

Cover image for JS Refactoring Combo: Simplify If-Else Variable Initialization
Lars Grammel for P42

Posted on • Edited on • Originally published at p42.ai

4 2

JS Refactoring Combo: Simplify If-Else Variable Initialization

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (1)

Collapse
 
harithzainudin profile image
Muhammad Harith Zainudin

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay