Home  >  Article  >  Web Front-end  >  How to write clean JS code? 5 writing tips to share

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

青灯夜游
青灯夜游forward
2022-08-15 20:16:051544browse

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;
}

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;
}

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 {
    // ...
  }
}

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) => {
  // ...
}

3. Encapsulate multiple conditions

We often write code like this:

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

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) {
  // ...
}

or

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

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)) {
  // ...
}

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)) {
  // ...
}

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){
    //...
}

Rewritten as map:

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

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;
}

Rewritten as an array:

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

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!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete