Skip to content

How to refactor multiple if statements JavaScript

  • by

Refactoring multiple if statements in JavaScript can make your code more concise and easier to read.One way to refactor multiple if statements are by using a switch statement.

A switch statement allows you to evaluate an expression and execute code based on the result of that expression.

switch(expression) {
  case value1:
    // code to execute if expression equals value1
    break;
  case value2:
    // code to execute if expression equals value2
    break;
  default:
    // code to execute if expression does not equal any of the values
}

While a switch statement can improve code readability, it’s important to weigh the benefits and drawbacks before implementing it in your code.

Refactor multiple if statements JavaScript example

Simple example code of how you can use a switch statement to refactor multiple if statements:

Let’s say we have the following code:

if (fruit === 'apple') {
  console.log('It is an apple');
} else if (fruit === 'orange') {
  console.log('It is an orange');
} else if (fruit === 'banana') {
  console.log('It is a banana');
} else {
  console.log('It is an unknown fruit');
}

We can refactor this code using a switch statement:

switch(fruit) {
  case 'apple':
    console.log('It is an apple');
    break;
  case 'orange':
    console.log('It is an orange');
    break;
  case 'banana':
    console.log('It is a banana');
    break;
  default:
    console.log('It is an unknown fruit');
}

The switch statements can sometimes be less efficient than using if statements, especially when dealing with a large number of cases.

Using a function and passing values for the fruit variable:

<!DOCTYPE html>
<html>
  <body>    
    <script>
    function checkFruit(fruit) {
    switch(fruit) {
        case 'apple':
            console.log('It is an apple');
            break;
        case 'orange':
            console.log('It is an orange');
            break;
        case 'banana':
            console.log('It is a banana');
            break;
        default:
            console.log('It is an unknown fruit');
        }     
    }

    // Call the function with different fruits
    checkFruit('apple');
    checkFruit('orange');
    checkFruit('banana');
    checkFruit('watermelon');

    </script>
  </body>
</html>

Output:

How to refactor multiple if statements JavaScript

OR operator

The OR operator evaluates each operand and returns the first truthy value.

if (fruit === 'apple' || fruit === 'orange' || fruit === 'banana') {
  console.log('It is a known fruit');
} else {
  console.log('It is an unknown fruit');
}

We can refactor this code using the OR operator like this:

if (['apple', 'orange', 'banana'].includes(fruit)) {
  console.log('It is a known fruit');
} else {
  console.log('It is an unknown fruit');
}

Nullish coalescing

The nullish coalescing operator returns the first defined value of two operands, or null or undefined if both operands are null or undefined.

let price;

if (product && product.price) {
  price = product.price;
} else {
  price = 0;
}

We can refactor this code using the nullish coalescing operator like this:

let price = product?.price ?? 0;

Optional chaining

The optional chaining operator allows you to access the properties of an object without causing an error if the object or any of its properties are null or undefined.

if (person && person.address && person.address.city) {
  console.log('City:', person.address.city);
} else {
  console.log('City is not available');
}

Refactor this code using the optional chaining operator like this:

console.log('City:', person?.address?.city ?? 'City is not available');

No-else-returns and guard clauses

The “no-else-returns” pattern involves restructuring your code so that all return statements are at the top level of your function.

function getDiscount(price, user) {
  if (user && user.isPremium) {
    return price * 0.2;
  }
  return price * 0.1;
}

Refactor this code using the “no-else-returns” pattern like this:

function getDiscount(price, user) {
  if (user && user.isPremium) {
    return price * 0.2;
  }
  return price * 0.1;
}

Comment if you have any doubts or suggestions on this Js if statement topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading