4 ways to help you write conditional sentences better in JavaScript

Tram Ho

When working with JavaScript, we often encounter many conditional statements, here are 5 ways to help you clean code that you learn. Let’s go! ?

1. Use Array.includes with many conditional expressions

See an example:

At first glance, the example above looks good. But if you need to check lots of fruit then your code will be verbose with lots of || . Once there, you can use Array.includes under conditional expressions to check them.

We have gathered redFruit into an array so we can use includes . This makes your code much cleaner, isn’t it. ?

2. The content of the condition is less so it should be returned first

Expanding on the example above, we have 2 conditions

  • If fruit does not exist, quẳng it an error ?
  • If redFruit contains fruit and the quantity greater than 10

Let’s see an example

A general rule that you should follow is that of what is invalid, we should handle them first and return if necessary. We can tidy up the above code by reversing the conditional statements. Try it

This way your code will be more concise, and less nested in an if , and conditional reversal will help you think better.

3. Use default parameters for Function and Destructuring

For the example below, we always check for a null / underfined input underfined and assign it a default value when working in JavaScript.

In fact they can ‘save’ a variable q by assigning a default value to the quantity parameter

So what if fruit is an Object , can we assign default values ​​to them?

Looking at the example above, we will have to check the existence of fruit && fruit.name . But using destructuring and assigning default values ​​for it will not have to check so

4. Use Array.every and Array.some for partial or partial conditional expressions

In this final tip, let’s get back to the Array method. For the following example, I want to check all fruit of the same color

Do you find the code is too long, we can reduce the number of lines of code using Array.every

Much cleaner ? . Similarly, we can also check for at least one red fruit with Array.some

Above are 4 ways you can clean your code more when using conditional statements in JavaScript. Thanks for watching. ?

The article is available at: Tips JavaScript

Share the news now

Source : Viblo