“This article has participated in the call for good writing activities, click to view: the back end, the big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!”

preface

When working with JavaScript, we often have to deal with a lot of conditional statements. Here are some tips to help you write better/clearer conditional statements. At the same time, this article is also the application of some practical scenarios for learning these little-known coding skills in the previous article.

In the flowers, flowers gift gentleman; If you smile, leave praise and love.

What about multiple conditions

Let’s look at the following example:

JavaScript code:

function test(animal) {
  if (animal == 'cat' || animal == 'dog'||animal == 'cattle') {
    console.log('yes'); }}Copy the code

The conditional statement in the test function looks fine, but what if you add several? The analogy is sheep, pig, chicken, at this time looking at our conditional statement, has been very bloated.

function test(animal) {
  if (animal == 'cat' || animal == 'dog'||animal == 'cattle'||animal == 'sheep'||animal == 'pig'||animal == 'chicken') {
    console.log('yes'); }}Copy the code

This code already looks pretty bad for readability and maintainability, and if you add some conditions to it, you’ll get annoyed. Logic or | | have apparently not very suitable for this kind of scenario, we can use the Array. The statement includes rewrite the above conditions.

function test(animal) {
// The condition is extracted into the array
  const yesArr = ['cat'.'dog'.'cherry'.'cattle'.'sheep'.'pig'.'chicken'];
 
  if (yesArr.includes(animal)) {
    console.log('yes'); }}Copy the code

So if I write it this way, it’s clear, and the code looks a lot cleaner.

A nice return statement

Let’s extend the previous example to include two more conditions:

  • Throw an error if an animal/non-animal is not provided
  • Number of accepted animalsnumber(Quantity) parameter, if more than 20, and print the related information.
function test(animal, number) {
  const yesArr = ['cat'.'dog'.'cherry'.'cattle'.'sheep'.'pig'.'chicken'];
 
  // Condition 1: animal must have a value
  if (animal) {
    // Condition 2: must be yesArr animal
    if (redFruits.includes(animal)) {
      console.log('yes');
      // Condition 3: Quantity must be greater than 10
      if (number > 20) {
        console.log('quite a lot'); }}}else {
    throw new Error('No animal! '); }}// Test results
test(null); // Throw an error: No animal!
test('cat'); // Print: yes
test('cat'.20); // Prints: yes, quite a lot
Copy the code

This is our usual handy code, it seems that there is no problem, but is there room for optimization? Looking at the code above, we have:

  • An if/else statement filters out invalid conditions
  • Layer 3 nesting of if statements (conditions 1,2 and 3, respectively)

Advance when invalid conditions are foundthrow new Error. Give it a try

function test(animal, number) {
    const yesArr = ['cat'.'dog'.'cherry'.'cattle'.'sheep'.'pig'.'chicken'];
    // Condition 1: Animal must have a value, otherwise an error is thrown ahead of time
    if(! animal)throw new Error('No animal! ');
    // Condition 2: must be yesArr animal
    if (redFruits.includes(animal)) {
      console.log('yes');
      // Condition 3: Quantity must be greater than 10
      if (number > 20) {
        console.log('quite a lot'); }}}// Test results
test(null); // Throw an error: No animal!
test('cat'); // Print: yes
test('cat'.20); // Prints: yes, quite a lot
Copy the code

As you can see, it looks much more comfortable with one less layer of nesting. When we were watching old company projects, did the long if(){}else if(){} words make you burst into tears, while crying, MMP kept looking for the problem? Welcome to harangue the if () {} else if () {} in the comments section images, let HXD also can feel your pain, you are not a person in pain 😫, there is a pile of HXD beside you close ranks (than miserably contest without moral 😂 laugh ~)

Getting back to the point, we can further reduce nesting by reversing conditions and returning earlier. Check out Condition 2 below to see how we did it:

function test(animal, number) {
    const yesArr = ['cat'.'dog'.'cherry'.'cattle'.'sheep'.'pig'.'chicken'];
    // Condition 1: Animal must have a value, otherwise an error is thrown ahead of time
    if(! animal)throw new Error('No animal! ');
    // Condition 2: must be yesArr animal
    if(! redFruits.includes(animal))return
    // Condition 3: Quantity must be greater than 10
    if (number > 20) {
    console.log('quite a lot'); }}// Test results
test(null); // Throw an error: No animal!
test('cat'); // Print: yes
test('cat'.20); // Prints: yes, quite a lot
Copy the code

As you can see, reducing the use of a conditional statement can not only save performance, but also greatly improve the readability and pleasure of the code, at least it looks comfortable, there will be no pain to understand!! It can be concluded that

  • With less nesting, the code looks much more comfortable
  • Less nesting, less thinking, less hair loss

Go for less nesting, return early, but don’t overdo it.

Strong wine is good, but do not drink oh ~

Function default arguments and destructions

Always check for null/undefined values and assign defaults when using JavaScript:

function test(animal, number) {
  if(! animal)return;
  const count = number || 1; // If no number argument is provided, the default is 1
 
  console.log(`${count}only${animal}! `);
}
 
// Test results
test('pig'); / / 1 a pig!
test('pig'.2); / / 2 a pig!
Copy the code

We can eliminate the variable count by assigning default function arguments,

function test(animal, number=1) {
  if(! animal)return;
  console.log(`${number}only${animal}! `);
}
 
// Test results
test('pig'); / / 1 a pig!
test('pig'.2); / / 2 a pig!
Copy the code

What if our animal is an Object? Can we specify default parameters? The answer is yes.

function test(animal) { 
  // If there is a value, print animal.name
  if (animal && animal.name)  {
    console.log (animal.name);
  } else {
    console.log('what??? '); }}// Test results
test(undefined); // what???
test({ }); // what???
test({ name: 'pig'.sex: 'boy' }); // pig
Copy the code

Looking at the example above, we want to print the fruit name if animal.name is available, otherwise print what??. We can avoid checks like animal && Animal. name by using the default function arguments and destructing.

function test({name}={}) { 
  console.log (name || 'what??? ');
}
 
// Test results
test(undefined); // what???
test({ }); // what???
test({ name: 'pig'.sex: 'boy' }); // pig
Copy the code

Since we only need the name attribute from Animal, we can use {name} to deconstruct the parameter, and then we can use name as a variable in our code instead of Animal.name.

We also specify the null object {} as the default. If we don’t do this, You will get test(undefined) — Cannot destructure property name of ‘undefined’ or ‘null’. Because undefined doesn’t have a name attribute.

Is the Switch statement really good?

For an example, print the fruit by color

function test(color) {
  // Use the switch case statement to find the corresponding fruit by color
  switch (color) {
    case 'red':
      return ['apple'.'strawberry'];
    case 'yellow':
      return ['banana'.'pineapple'];
    case 'purple':
      return ['grape'.'plum'];
    default:
      return[]; }}// Test results
test(null); / / []
test('yellow'); // ['banana', 'pineapple']
Copy the code

Does the code look wordy? Is there a better way to write it? Try using object literals with a clearer syntax.

// Use the object literal to find the corresponding fruit by color
  const fruitColor = {
    red: ['apple'.'strawberry'].yellow: ['banana'.'pineapple'].purple: ['grape'.'plum']};function test(color) {
  return fruitColor[color] || [];
}
Copy the code

Try using Map:

// Use Map to find the corresponding fruit by color
  const fruitColor = new Map()
    .set('red'['apple'.'strawberry'])
    .set('yellow'['banana'.'pineapple'])
    .set('purple'['grape'.'plum']);
 
function test(color) {
  return fruitColor.get(color) || [];
}
Copy the code

Map is a new object type introduced in ES2015(ES6) that allows you to store key-value pairs.

I could write it a simpler way

Array.filter is also available. The fun of coding needs to be experienced by heart. What is happy planet??

 const fruits = [
    { name: 'apple'.color: 'red' }, 
    { name: 'strawberry'.color: 'red' }, 
    { name: 'banana'.color: 'yellow' }, 
    { name: 'pineapple'.color: 'yellow' }, 
    { name: 'grape'.color: 'purple' }, 
    { name: 'plum'.color: 'purple'}];function test(color) {
  // Use Array filter to find the corresponding fruit by color
  return fruits.filter(f= > f.color == color);
}
Copy the code

There are always surprises, like when I met you.

Array.every and array. some handle conditional statements

Using the Javascript Array function can effectively reduce the number of lines of code. Here is the code:

const fruits = [
    { name: 'apple'.color: 'red' },
    { name: 'banana'.color: 'yellow' },
    { name: 'grape'.color: 'purple'}];function test() {
  let isAllRed = true;
 
  // Condition: All fruit must be red
  for (let f of fruits) {
    if(! isAllRed)break;
    isAllRed = (f.color == 'red');
  }
 
  console.log(isAllRed); // false
}
Copy the code

Use array. every to try:

const fruits = [
    { name: 'apple'.color: 'red' },
    { name: 'banana'.color: 'yellow' },
    { name: 'grape'.color: 'purple'}];function test() {
  // Condition: Short way, all fruit must be red
  const isAllRed = fruits.every(f= > f.color == 'red');
 
  console.log(isAllRed); // false
}
Copy the code

If we want to check if at least one fruit is red, we can use array.some with just one line of code.

const fruits = [
    { name: 'apple'.color: 'red' },
    { name: 'banana'.color: 'yellow' },
    { name: 'grape'.color: 'purple'}];function test() {
  // Condition: is there any red fruit
  const isAnyRed = fruits.some(f= > f.color == 'red');
 
  console.log(isAnyRed); // true
}
Copy the code

conclusion

Proper use of some skills, not only can make your Coding speed and quality get sublimation, but also can play an inestimable value. After all, you can’t put a price on what makes someone happy, can you?

Write in the last

I am Liangcheng A, a front-end, love technology and love life.

I’m very happy to meet you.

If you want to learn more, please click here and look forward to your little ⭐⭐

  • If there are any errors, please correct them in the comments section. If this article helped you, please like 👍 and follow 😊

  • This article was first published in nuggets. Reprint is prohibited without permission 💌