Home > Web Front-end > JS Tutorial > body text

How to write clean JS code? 5 writing tips to share

青灯夜游
Release: 2022-08-16 13:03:19
forward
1569 people have browsed it

How to write clean JS code? In this article, I will share with you 5 tips for writing clean JavaScript. I hope it will be helpful to you!

How to write clean JS code? 5 writing tips to share

Reduce the reading burden, inspire the creative mind, easily learn JavaScript skills, jym, rush~

1. Change the numbers Defined as a constant

We often use numbers, such as the following code:

const isOldEnough = (person) => {
  return person.getAge() >= 100;
}
Copy after login

Who knows what this 100 specifically refers to? We usually need to combine the function context to speculate and judge what value this 100 may specifically represent.

If there are multiple such numbers, it will easily cause greater confusion.

Write clean JavaScript: Define numbers as constants

This problem can be solved clearly:

const AGE_REQUIREMENT = 100;
const isOldEnough = (person) => {
  return person.getAge() >= AGE_REQUIREMENT;
}
Copy after login

Now, we declare the constant name, you can immediately understand that 100 means "age requirement". When modifying, you can quickly locate it, modify it in one place, and take effect in multiple places.

2. Avoid using Boolean values ​​as function parameters

Passing Boolean values ​​into functions as parameters is a common writing method that easily causes code confusion.

const validateCreature = (creature, isHuman) => {
  if (isHuman) {
    // ...
  } else {
    // ...
  }
}
Copy after login

The Boolean value passed into the function as a parameter cannot express a clear meaning. It can only tell the reader that this function will make a judgment and produce two or more situations.

However, we advocate the Single Responsibility Principle for functions, so:

Write Clean JavaScript: Avoid Boolean values ​​as function parameters

const validatePerson = (person) => {
  // ...
}
const validateCreature = (creature) => {
  // ...
}
Copy after login

3. Encapsulate multiple conditions

We often write code like this:

if (
  person.getAge() > 30 &&
  person.getName() === "simon" &&
  person.getOrigin() === "sweden"
) {
  // ...
}
Copy after login

It’s not impossible, but after a long time, you will not be able to understand these judgments. What exactly is it going to do, so it is recommended to encapsulate these conditions with variables or functions.

Write clean JavaScript: encapsulate multiple conditions

const isSimon =
  person.getAge() > 30 &&
  person.getName() === "simon" &&
  person.getOrigin() === "sweden";
if (isSimon) {
  // ...
}
Copy after login

or

const isSimon = (person) => {
  return (
    person.getAge() > 30 &&
    person.getName() === "simon" &&
    person.getOrigin() === "sweden"
  );
};
if (isSimon(person)) {
  // ...
}
Copy after login

Oh, it turns out that these conditions are to determine whether this person is Simon ~

This kind of code is declarative style code, which is more readable.

4. Avoid negative judgment conditions

In conditional judgments, using negative judgments will cause an additional burden of thinking.

For example, in the following code, the condition !isCreatureNotHuman(creature) is a double negative, which makes it a bit difficult to read.

const isCreatureNotHuman = (creature) => {
  // ...
}

if (!isCreatureNotHuman(creature)) {
  // ...
}
Copy after login

Write clean JavaScript: avoid negative judgment conditions

It is easier to read by rewriting it into the following writing rules. Although this is only a small trick, but In a large amount of code logic, it will definitely be helpful to follow this principle in many places.

Many times when reading code, I just read and read. When I see a "bad" writing method, I can't stand it anymore. Details will be superimposed, and a thousand-mile dike will collapse in an ant nest.

const isCreatureHuman = (creature) => {
  // ...
}
if (isCreatureHuman(creature)) {
  // ...
}
Copy after login

5. Avoid a lot of if...else...

This point has always been emphasized:

For example, the following code :

if(x===a){
   res=A
}else if(x===b){
   res=B
}else if(x===c){
   res=C
}else if(x===d){
    //...
}
Copy after login

Rewritten as map:

let mapRes={
    a:A,
    b:B,
    c:C,
    //...
}
res=mapRes[x]
Copy after login

Another example is the following code:

const isMammal = (creature) => {
  if (creature === "human") {
    return true;
  } else if (creature === "dog") {
    return true;
  } else if (creature === "cat") {
    return true;
  }
  // ...
return false;
}
Copy after login

Rewritten as an array:

const isMammal = (creature) => {
  const mammals = ["human", "dog", "cat", /* ... */];
  return mammals.includes(creature);
}
Copy after login

Write cleanly JavaScript: Avoid a lot of if...else...

So, when there are a lot of if...else... in the code, think one more step and see if the code can be slightly modified. Looks "cleaner".


Summary: The above techniques may not seem worth mentioning in examples, but in actual projects, when the business logic becomes complex and the amount of code becomes large, these tips will definitely It can provide positive effects and help, even beyond imagination.

[Related recommendations: javascript learning tutorial]

The above is the detailed content of How to write clean JS code? 5 writing tips to share. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!