Home > Web Front-end > JS Tutorial > Detailed explanation of how JavaScript reduces function complexity

Detailed explanation of how JavaScript reduces function complexity

青灯夜游
Release: 2021-01-15 18:58:37
forward
3477 people have browsed it

Detailed explanation of how JavaScript reduces function complexity

JavaScript is an easy-to-learn programming language, and it’s easy to write programs that run and perform certain actions. However, writing clean JavaScript code is difficult.

In this article, we will look at how to reduce function complexity.

Move the duplicate code to the same location

We should extract the duplicate code and merge it into the same location, so When something needs to be modified, we only need to change one place, which also reduces the error rate.

Suppose we can easily write the following code:

const button = document.querySelector('button');
let toggled = true;
button.addEventListener('click', () => {
  toggled = !toggled;
  if (toggled) {
    document.querySelector("p").style.color = 'red';
  } else {
    document.querySelector("p").style.color = 'green';
  }
})
Copy after login

There are two document.querySelector(“p”) in the above code, we can optimize it like this, Save document.querySelector(“p”) to a variable, and then use the variable, as shown below:

const button = document.querySelector('button');
const p = document.querySelector("p");
let toggled = true;
button.addEventListener('click', () => {
  toggled = !toggled;
  if (toggled) {
    p.style.color = 'red';
  } else {
    p.style.color = 'green';
  }
}
Copy after login

This way we don’t have to write a long document.querySelector("p"), just write a variable p.

The numbers in another common code example, it is difficult for us to know what they represent just by looking at the numbers:

let x = 1;
let y = 1;
let z = 1;
Copy after login

We don’t know what the three ones above represent, so we can move Remove duplicate code and represent it with a suitable variable name, as follows:

const numPeople = 1;
let x = numPeople;
let y = numPeople;
let z = numPeople;
Copy after login

So we can know that the value of numPeople is 1, which represents number of people.

Simplified function

The function should be as simple as possible. It is best to only do one thing. The number of lines should not be too many. The maximum number should not be more than 30 lines.

We should not use ES5 classes, nor IIFE for modules or blocks. Instead, we should use class syntax where we can include multiple instance methods of the class within a class. This will greatly reduce the size of the function.

Similarly, as long as we can define functions, functions should be pure functions, which means they should not have side effects.

For example, the best simple function is the following:

const add = (a, b) => a + b;
Copy after login

The above function does not have any side effects because it does not modify any variables outside the function. In addition, it is also a pure function. For the same input, the output result is also the same.

Use guard statements instead of nested statements

Definition and usage of guard statements

Guard statements are complex statements The conditional expression is split into multiple conditional expressions. For example, a very complex expression nested with several layers of if-then-else statements is converted into multiple if statements to implement its logic. These multiple The if statement is a guard statement

Sometimes the conditional may appear in the nest n times before it can be actually executed, and other branches simply report an error and return. In this case, the branch that reports an error should be checked separately. , returns immediately when the condition is true, such a separate check is a guard clause (guard clauses). Guard clauses can liberate our eyes from exception handling and concentrate on normal processing code.

For example, we may write the following code:

const greet = (firstName, lastName, greeting) => {
  if (typeof firstName === 'string') {
    if (typeof lastName === 'string') {
      if (typeof greeting === 'string') {
        return `${greeting}, ${firstName}${lastName}`;
      }
    }
  }
}
Copy after login

We can optimize like this

const greet = (firstName, lastName, greeting) => {
  if (typeof firstName !== 'string') {
    throw new Error('first name is required');
  }
  if (typeof lastName !== 'string') {
    throw new Error('last name is required');
  }
  if (typeof greeting !== 'string') {
    throw new Error('greeting is required');
  }
  return `${greeting}, ${firstName}${lastName}`;
}
Copy after login

In the second example, if each parameter is not a string, then Throws an error, thus eliminating nested if statements.

This reduces nested if statements to unnested if statements while performing the same operation.

Nests are hard to read and understand, and we should get rid of them everywhere.

Summary

Duplicate code is always bad. We should always remember the “Don’t Repeat Yourself (DRY)” principle.

In addition, some new methods should be used to replace the writing methods in the ES5 era.

Finally, nested if statements should be replaced with guard statements because they can perform the same checks as nested if statements, which facilitates reading .

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of Detailed explanation of how JavaScript reduces function complexity. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template