20 tips for learning javascript's programming conventions

  • 2020-03-30 04:25:04
  • OfStack

1, using js file management code

Try to put all the code in a js file, and then use script to introduce it in an HTML file. When you introduce it, put it after the body tag, and do not use type or language.

2. Write indentation

Use 4 blank Spaces to indent, be careful not to use the TAB key to indent.

3,

Note that the line length, each line is not more than 80 characters, exceeding the appropriate sentence break, the sentence should be after the operator, the best is the comma (,) after the sentence break, the next line after the sentence use 8 indentation.

4, annotations,

Single-line comments are generally used, and block comments are generally used for documents.

5. Variable declaration

All variables are declared before they are used, and undeclared variables are automatically treated as global variables. Global variables should be used sparingly throughout the text.
It is better to implement all variable declarations with a var, and put a separate line for each declaration, and add comments. If all declared variables can be listed in character order, as follows:


var currentEntry,      //Currently select table item
    level;          //Indentation level

When all variables are defined at the top of the body, var appears at the beginning of the body.

6. Function declaration

All functions should be declared before they are used and followed by variables - it helps to see the scope.
Function names and parentheses should not have Spaces directly; Close parenthesis (there should be no Spaces between function arguments; Left parenthesis) and function body parenthesis {there is a space between; The body of the function is indented with 4 Spaces. Function body closing bracket} and function declaration keyword function first character alignment. The following code:


function outer(c,d) {
    var e = c * d;     function inner(a,b) {
        return (e * a ) + b;
    }     return inner(0,1);
}

Functions and objects can be placed wherever expressions are allowed.
The anonymous function keyword function and the open parenthesis (with a space between them.
Minimize the use of global functions.
For functions that execute immediately, the entire call expression should be enclosed in a pair of parentheses () to make it clear that the value of the variable is the result of the function's execution and not the function itself. The following code:

var result = (function () {
    var key = "";
    return {
        get: function () {
            return key;
        },
        set: function (key) {
            key = key;
        }
    };
}());

7, named

Name them after letters, Numbers, and underscores. Avoid international characters, the dollar sign $, and backslashes.
Do not use an underscore as the first character of a name.
Most variables and functions are named with a lowercase letter.
Constructors must begin with a capital letter, and omitting new in js does not cause errors (compile or run errors), but it is best not to omit it.
Global variables are named in all uppercase (js has no concept of macros and constants).

8, statements,

A simple statement

Maximum one statement per line, using semicolons; At the end, note that the semicolon is also used for statements that assign values to function literals and object literals. .
Js allows any variable to be a statement, but it may cause some errors when inserting semicolons, so the statements that usually use expressions are assignment or function call statements.

Compound statements (statements contained between a pair of {})

Indent the inner statement with four Spaces.

The left parenthesis {should be at the end of the starting statement line.
The right parenthesis should be on a separate line at the end and aligned with the first character of the line with the left parenthesis.
When statements are in control statements (such as for, if, and so on), you should surround them with curly braces {}, even if there is only one statement, to ensure that there are no bugs when you add statements.

9, labels, (this part of the understanding is not quite right)

The statement to use label is optional, with only the following: while, for, do, switch.

Return statement

The value returned should be enclosed in parentheses, and the return expression should be on the same line as the return keyword (avoid semicolons for newlines).

11. If statement

Follow the following format:


if (condition) {
    statements
} if (condition) {
    statements
} else {
    statements
} if (condition) {
    statements
} else if (condition) {
    statements
} else {
    statements
}

12. For statement

Follow the following format:


for (initiliazation; condition; update) {
    statements
} for (variable in object) {
    if (filter) {
        statements
    }
}

The first loop format is used for arrays and variables that can determine the number of iterations.
The second is used for object traversal
Note: it was mentioned here that the properties added to the object prototype can be enumerated, so the hasOwnProperty method was used for filtering, but it didn't show up when I tested it with the for in code, so I didn't know what the problem was.

13. While statement

Follow the following format:


while (condition) {
    statements
}

14. Do -while statement

Follow the following format:


do {
    statements 
} while (condition);

A semicolon is added at the end of the statement.

15. Switch statement

Follow the following format:


switch (expression) {
case expression:
    statements
default:
    statements
}

Every case should be aligned with the switch to avoid excessive indentation. Only the case label is not a statement and should be indented.
Every case statement (except default) must end with a break or return or throw.

16. Try statement

Follow the following format:


try {
    statements
} catch (variable) {
    statements
}
try {
    statements
} catch (variable) {
    statements
} finally {
    statements
}

17. Continue statement

Avoid the continue statement.

18, with statement

The with statement should not be used.

19. Use of Spaces

To enhance the readability of the code, empty lines are set to separate logically related code segments.
Set a space when:
The keyword is followed by an open parenthesis (to use a space, for example:
While (true) {
You cannot use a space between a function argument and an open parenthesis.
Binary operators except for the dot (.), the left parenthesis ((), and the square parenthesis ([)) use a space to separate the operands.
There should be no space between a unary operator other than typeof and its operands.
The for statement controls each semicolon in the block (); There's a space after that.
Each comma should be followed by a space.

20. Extra advice

[] and {}
Arrays are used when the member names are consecutive integers, and objects are used when the member names are arbitrary strings and names.
Replace new object() with {} and new Array() with [].
Comma operator
Avoid commas and operators (this rule does not apply to object literals, array literals, var declarations, and parameter lists)
Block-level scope
In addition to not using statement blocks for conf statements, js has no block-level scope, only function scope.
Assignment expression
Avoid using assignment statements in the conditional judgment portion of while and if statements.
= = = and! = =
Equality is determined using the congruent notation (=== and! ==), avoid using a type equality cast symbol (== and! =).
If a number is added (or -) to a number with a sign (+ or -), or a number with (++ or --), then the number with a sign or (++ or --) is enclosed.
Eval is evil.
Eval does the same thing. You should not use the Function constructor, and you should not pass a string to a setTimeout or setInterval Function.

The above 20 Suggestions are summarized in the project, for the novice learning javascript should be a small help, are personal experience, it is inevitable that there is a comprehensive place, if found, please also tell, here to draw lessons, we make progress together.


Related articles: