DEV Community

56kode
56kode

Posted on

Clean Code: Writing clear conditional logic in JavaScript

Let's first look at a common way to write conditions:

// Without function encapsulation
if (state === "fetching" && isEmpty(itemsList)) {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

This code has several problems:

  • You need to read and understand the logic inside the if statement
  • If you need this check in other places, you'll likely copy-paste it
  • Adding new conditions makes the if statement longer and harder to read

Here's a better approach:

function shouldShowSpinner(state, itemsList) {
  return state === "fetching" && isEmpty(itemsList);
}

if (shouldShowSpinner(currentState, currentItemsList)) {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

This approach brings 4 main benefits:

  1. Better readability: Instead of reading through the logic inside the if statement, you can understand what the code does by reading the function name shouldShowSpinner.

  2. Code reuse: You can use the same condition in different parts of your code by calling the function, avoiding copy-paste.

  3. Easier maintenance: When you need to change the logic, you only change it in one place - inside the function. For example, if you need to add a new condition:

function shouldShowSpinner(state, itemsList) {
  return state === "fetching" && 
         isEmpty(itemsList) && 
         !hasError(state);
}
Enter fullscreen mode Exit fullscreen mode
  1. Simpler testing: You can write focused tests for the function to make sure your conditional logic works correctly.

This practice works best for conditions that:

  • Have multiple parts
  • Need to be used in several places
  • Express an important business rule
  • Might change in the future

Start small - look for complex if statements in your code and try putting them into functions with clear names. You'll see how much easier your code becomes to read and maintain.

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 (0)

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