This article introduces the tips for improving the readability of JavaScript code. Here we will introduce the methods. For more information, see.
Flattening Logic
In our work, we may encounter some complicated logic, such as: Meet condition 1, or XX; meet condition 2, or XX ...... If all of these conditions are met, write them like this:
The Code is as follows: |
Copy code |
If (condition1 ){ If (condition2 ){ If (condition3 ){ // Do // // Lot } Else { // Do zz } } Else { // Do oo } } Else { // Do xx } |
The result is that the nested logic is complex and hard to read. It would be even worse if the indentation was not completed or the line feed was not completed. In this case, code execution can be interrupted in advance to flatten the logic. Methods for early interruption include return, throw, and die () and exit () in PHP (). The Code is as follows:
The Code is as follows: |
Copy code |
If (! Condition1 ){ // Do xx Return; }
If (! Condition2 ){ // Do oo Return; }
If (! Condition3 ){ // Do zz Return; }
// Do // // Lot |
Of course, this method is also applicable where exceptions need to be ruled out. There are even radical comments that else should not be used, but should be interrupted in advance. I think that is a little too much. The significance of if... else... is still very clear.
Shorten long logical judgment
There is an unwritten rule from the ancient times that a line of code contains 80 characters. As the monitor grows, this old rule should be broken. However, if a single line of code is too long, it may seem very tiring, so we still need to control it. Super-long code is often used in logic judgment. For example, the Code commonly used in the game to detect whether a bullet has hit a player is written in a good format, which is probably like this:
The Code is as follows: |
Copy code |
If (bullet. x> enemy. x + enemy. width | bullet. y> enemy. y + enemy. height | bullet. x + bullet. width <enemy. x | bullet. y + bullet. width <enemy. y ){ Console. log ('not hitting '); } |
This is no longer short. Sometimes we need to add enemy. damagable and ,! Other conditions such as enemy. immunePhysical determine the write length of this row. At this time, we need to use some tips to shorten it. There may be a variety of methods, and the idea is the same, that is, refining the "purpose"-refining the purpose of a group of judgments into a variable, both good read and can shorten the code. Next, let's use a piece of code to explain it:
The Code is as follows: |
Copy code |
Var isGod =! Enemy. damagable | eneymy. immunePhysical, // determines whether the enemy cannot attack/God Mode IsHit = bullet. hitTest (eneymy); // "collision detection" If (! IsGod & isHit ){ Enemy. die (); }
|
Summary
Both tips are simple, but the code readability is improved significantly. A variety of tips are combined to make the Code better read and easier to maintain.