How to use JavaScript to write better conditional statements in detail

  • 2021-08-06 20:11:04
  • OfStack

Directory Preface 1. Array Methods Array. includes
2. Early exit/early return
3. Replace the Switch statement with an object literal or Map
4. Default parameters and deconstruction
5. Use Array. every & Array. some Match All/Parts
6. Combine with optional chains and null values
Summarize

Preface

In any programming language, the code needs to make different decisions and perform corresponding actions in a given input according to different conditions.

For example, in 1 game, if the player's life point is 0, the game ends. In the weather app, if viewed in the morning, a sunrise picture is displayed, and if it is in the evening, the stars and moon are displayed. In this article, we will explore how the so-called conditional statements in JavaScript work.

If you work with JavaScript, you will write a lot of code containing conditional calls. Conditional calls may be easy to learn, but there's more to it than writing a pair of if/else. Here are some useful tips for writing better and clearer conditional code.

1. Array Method Array. includes

Use Array. includes for multi-condition selection

For example:


 function printAnimals(animal) {
 if (animal === 'dog' || animal === 'cat') {
  console.log(I have a ${animal});
 }
 }

 console.log(printAnimals('dog')); // I have a dog

The above code looks good because we only checked two animals. However, we are not sure about the user input. What if we're going to examine any other animals? If we extend by adding more "or" statements, the code becomes difficult to maintain and unclear.

Solution:

We can override the above condition by using Array. includes


 function printAnimals(animal) {
  const animals = ['dog', 'cat', 'hamster', 'turtle'];

  if (animals.includes(animal)) {
   console.log(I have a ${animal});
  }
 }

 console.log(printAnimals('hamster')); // I have a hamster

Here we create an array of animals so that conditional statements can be abstractly separated from the rest of the code. Now, if we want to check any other animals, we just need to add 1 new array entry.

We can also use the animal array variable outside the scope of the function to reuse it anywhere else in the code. This is a way to write code that is clearer, easier to understand and maintain, isn't it?

2. Early exit/early return

This is a very cool trick to streamline your code. I remember when I started working professionally, I learned on Day 1 to use early exit to write conditions.

Let's add more conditions to the previous example. An animal that replaces a simple string with an object containing a certain attribute.

The demand now is:

If there are no animals, throw 1 exception Print animal type Print animal names Print animal sex

const printAnimalDetails = animal => {
 let result; // declare a variable to store the final value

 // condition 1: check if animal has a value
 if (animal) {

  // condition 2: check if animal has a type property
  if (animal.type) {

   // condition 3: check if animal has a name property
   if (animal.name) {

    // condition 4: check if animal has a gender property
    if (animal.gender) {
     result = ${animal.name} is a ${animal.gender} ${animal.type};;
    } else {
     result = "No animal gender";
    }
   } else {
    result = "No animal name";
   }
  } else {
   result = "No animal type";
  }
 } else {
  result = "No animal";
 }

 return result;
};

console.log(printAnimalDetails()); // 'No animal'

console.log(printAnimalDetails({ type: "dog", gender: "female" })); // 'No animal name'

console.log(printAnimalDetails({ type: "dog", name: "Lucy" })); // 'No animal gender'

console.log(
 printAnimalDetails({ type: "dog", name: "Lucy", gender: "female" })
); // 'Lucy is a female dog'

What do you think of the code above?

It works well, but the code is long and difficult to maintain. If you don't use the lint tool, it takes a lot of time to find out where the closing curly braces are.


Related articles: