1. Browser debugging
F12
As we can see, there are three main ways to pause a script:
- A break point. (Type directly on the console)
- the
debugger
The statement. (Write debugger in code) - Error (if the developer is open and the button is “On”).
2, write code part specification
1, of course, vscode prettier can be configured to format code while saving
-
😠 Beginners sometimes do this. This is wrong, no curly braces needed:
if (n < 0) { alert(`Power ${n} is not supported`); } Copy the code
-
😠 splits into separate lines without curly braces. Never do this, adding new lines is error-prone:
if (n < 0) alert(`do somethings`); Copy the code
-
😏 line without braces – acceptable if it is short:
if (n < 0) alert(`do somethings`); Copy the code
2. Long sections are displayed in multiple lines as follows:
test(data1,
data2,
data3,
data4,
another
) {
// ...
}
Copy the code
3. Write the boundary conditions first if there are boundaries
- this is wrong
for (let i = 0; i < 6; i++) { if (code) { ... / /}}Copy the code
- this is right
for (let i = 0; i < 6; i++) { if (! code) continue; . / /}Copy the code
- More style details – Airbnb JavaScript Style Guide
Github.com/airbnb/java…
4. Code checking to use ESLint requires.eslintrc configuration
- The goal is to write code that is easy to read and conform to the specification
3. Write comments
1. Good code should be able to follow a method almost without comments to know what it is doing
2. Break down functions within a function into multiple functions
Sometimes it is beneficial to replace code snippets with functions, as shown below :(unsplit)
function test(n) { nextP: for (let i = 2; i < n; i++) { for (let j = 2; j < n; j++) { if (i % j == 0) continue nextP; } alert(i); }}Copy the code
- this is right
A better variant with decomposing features isPrime:
function test(n) { for (let i = 2; i < n; i++) { if (! nextP(i)) continue; alert(i); } } function nextP(n) { for (let i = 2; i < n; i++) { if (n % i == 0) return false; } return true; }Copy the code
3. Good comment structure
-
Record function arguments and usage
There is a special syntax, JSDoc, for recording functions: usage, arguments, return values.
Such as:
/**
* Returns x raised to the n-th power.
*
* @param {number} x The number to raise.
* @param {number} n The power, must be a natural number.
* @return {number} x raised to the n-th power.
*/
function pow(x, n) {
...
}
Copy the code
4. Other specifications
1, do not abbreviate the name
list
–lst
.userAgent
–ua
.browser
–brsr
.
2. When choosing a name, use the most abstract word possible. Like OBj, data, Value, item, elem, etc
3. Try to name a function with the function’s action starting with lower case
4. Do not use underscores arbitrarily. This can lead to confusion and wonder if this is a special use except for Lodash (there is a library _).
5, the code needs to be tested, there is an automated test library, we will talk about later