Objective:
The coding style of the programming language is important for a long term maintenance software, especially in team collaboration. If a team uses a uniform coding style, it can improve the team's level of collaboration and productivity. The core of the programming style guide is the basic formatting rules that determine how to write high standard code. This guide comes from writing maintainable JavaScript, based on the Java language encoding specification and Crockford JavaScript programming specification, as well as some of Nicbolas's personal experiences and preferences. Writing this article aims to deepen their impressions, but also for more people to understand the JS coding style, improve their coding quality. For more information, read "Writing maintainable JavaScript."
1. Indent
The hierarchy of each row consists of 4 spaces, avoiding the use of tab to indent.
A good spelling
if (true) {
dosomething ()
}
2. Length of line
The length of each line should not exceed 80 characters. If a row exceeds 80 characters, the line should be wrapped after an operator. The next line should increase the level two indent (8 characters).
Good spelling
dosomething (argument1, Argument2, Aegument3, Argument4,
argument5);
Bad writing: The second line has only 4 spaces indented
dosomething (argument1, Argument2, Aegument3, Argument4,
argument5);
3. Original value
The string should always use double quotes and keep a line, avoiding the use of a slash in a string to start another line.
Numbers should use decimal integers, scientific calculations represent integers, hexadecimal integers, or decimal floating-point decimals, which should retain at least one digit before and after a decimal. Avoid using octal direct quantities.
Special value NULL should be avoided except in the following cases.
• Used to initialize a variable that may be assigned to an object.
• Used to compare with an already initialized variable, this variable can or may not be an object.
• is used as a parameter when the parameter of the function is expected to be an object.
• is used as the return value when the return value of the function is expected to be an object.
Avoid using special value undefined. Determining whether a variable should be defined should use the TypeOf operator.
4. Operator spacing
You must use a space before and after the binary budget character to keep the expression neat. Operators include assignment operators and logical operators.
Good notation for
(var i = 0; i < count; i++) {
process (i);
}
Bad writing: Lost space for
(var i=0; i<count; i++) {
process (i);
}
5. Bracket Spacing
When you use parentheses, there should be no spaces immediately after the opening parenthesis and immediately before the closing parenthesis.
Good notation for
(var i = 0; i < count; i++) {
process (i);
}
Bad writing: There are extra spaces on both sides of the argument for
(var i = 0; i < count; i++) {
process (i);
}
6. Direct volume of objects
The object's direct quantity should have the following format.
• The starting left curly brace should remain on the same line as the expression.
• The name-value pairs for each attribute should be indented, and the first property should be followed by another line after the left curly brace.
• The name value pairs for each attribute should use a property name without quotes, followed by a colon (preceded by a space), followed by a value.
• If the property value is a function type, the function body should have a row under the property name, and should keep a blank line before and after it.
• A set of related properties can be inserted before and after a blank line to enhance the readability of the code.
• The closing curly brace should be exclusive to one line.
Good spelling
var object = {
key1:value1,
key2:value2,
func:function () {
//dosomething
},
Key3:value3
};
Bad wording: improper indentation of
var object = {
key1:value1,
key2:value2
};
Bad writing: Empty lines around the function body are missing
var object = {
key1:value1,
key2:value2,
func:function () {
// DoSomething
},
key3:value3
};
When an object literal is a function argument, if the value is a variable, the opening curly brace should be on the same line as the function name. All the remaining previously listed rules apply equally.
Good wording
dosomething ({
key1:value1,
key2:value2
});
Bad writing: All code dosomething on one line
({key1:value1, key2:value2});
7. Note
Use concise and clear annotations to help others understand your code. Comments should be used in the following situations.
• Code is obscure and difficult to understand.
• Code that may be mistaken for error.
• Necessary, but not obvious, browser-specific code.
• For objects, methods, or properties, it is necessary to generate documents (using appropriate documentation comments).
Single-line Comment
A single-line comment should be used to describe a line of code or a set of related code. There may be three ways to use single-line annotations.
• An exclusive line of comments to interpret the next line of code.
• A comment at the end of the line of code used to interpret the code before it.
• Multiple lines, used to comment out a block of code.
Good writing if
(condition) {
//If the code executes here, it means that all security checks are passed
allowed ();
}
Bad writing: note there is no blank line if
(condition) {
//If the code executes here, all security checks are passed
allowed ();
}
Bad writing: Wrong indent if
(condition) {
//If the code executes here, it means all security checks are passed
allowed ();
}
Bad writing: You should use a multiline comment
//code to make a * * judgment
//And then execute if
(condition) {
//If the code executes here, it means all security checks
allowed ( );
}
Good writing: When commenting at the end of a line, you should keep a space if
(condition) {
//If the code executes here, indicating that all security checks are passed
allowed ();//execute * * Function
}
//Bad writing: There is not enough space between the code and the annotation
(condition) {
//If the code executes here, all security checks are passed
allowed ();//execute * function
}
//Good writing: When commenting out a block of code, you should contact the use of a single-line annotation, which should not be used in multiple lines of comments.
//if (condition) {
// allowed ();//execute * * function
//}
Multiline Comment
Multiline comments should be used when the code needs more text to explain. There are at least three lines for each multiline comment:
1. The first line only includes/* Note start. The line should not have other text.
2. The following lines begin with a * and remain aligned to the left. These can be described in words.
3. The last line begins with/* and remains aligned with the previous line. There should be no other text.
The first line of a multiline comment should remain indented at the same level as the code it describes. Each successive line should have the same level of indentation and append a space (to properly maintain the alignment of the * character). A blank line should be reserved before every multiline code.
Good writing,
if (condition) {/
*
* If code execution is here
* Description passed all security checks
/allowed ();
}
Comment Declaration
Annotations can sometimes be used to declare additional information for a piece of code. The formats of these declarations begin with a single word and follow a colon. The declarations you can use are as follows.
TODO: The description code is not complete yet. Should contain the next thing to do.
HACK: Indicates that the code implementation has gone a short cut. Should include reasons why hack is used. This may also indicate that there may be a better solution to the problem.
XXX: Description The code is problematic and should be repaired as soon as possible.
Fixme: The description code is problematic and should be repaired as soon as possible. Importance is slightly more than XXX.
REVIEW: Explains that the code needs to be reviewed for any possible changes.
These declarations may be used in one or more lines of comments, and should follow formatting rules of the same annotation type.
8. Naming
Variables and functions should be named with care. Names should be limited to alphanumeric characters, and in some cases you can use underscores (_). It is best not to use the dollar sign ($) or the backslash (\) in any naming.
Variable naming should be in the hump naming format, with the first letter lowercase, and the first letter of each word capitalized. The first word of a variable name should be a noun (not a verb) to avoid confusion with the function. Do not use underscores in variable names.
Good writing
var accountnumber = "test001";
Bad writing: Capital letter at
the beginning of var accountnumber = "test001";
Bad writing: Verb at the beginning of
var getaccountnumber = "test001";
Bad writing: Use the underline
var account_number = "test001";
The function name should also be in the Hump naming format. The first word of a function name should be a verb (not a noun) to avoid confusion with the variable. It is best not to use underscores in function names.
Good writing
function dosomething () {
//code
}
//bad writing: Capital Letter opening
function dosomething () {
/ Code
}
//bad writing: noun opening
function something () {
//code
}
//Bad writing: Use underscore
function do_ Something () {
//code
}
constructor--a function that creates a new object by using the new operator--should also be named in the hump format and capitalized in the first character. The constructor name should begin with a non verb, because new represents an action that creates an object instance.
Good spelling
function MyObject () {
//code
}
//bad writing: lowercase letter opening
function MyObject () {
//code
}
//Bad writing: Use underscore
function My_object () {
//code
}
//bad writing: Verb opening
function getmyobject () {
//Code
}
The name of a constant (a variable with a value that is not changed) should be all uppercase letters, separated by a single underline between different words.
A good writing
var total_count = ten;
Bad wording: Hump form
var totalcount = ten;
Bad wording: Mixed form
var total_count = 10;
The properties of an object are the same as the naming rules for variables. The method of the object is the same as the naming rule for the function. If the property or method is private, you should precede it with an underscore.
Good spelling
var object = {
_count:10,4
_getcount:function () {return
this._count;
}
}
9. Variables and Function declarations
Variable declaration
All variables should be defined in advance before they are used. Variable definitions should be placed at the beginning of a function, using a var expression with one variable per line. In addition to the first row, all rows should be indented more than once to allow the variable names to be aligned vertically. Variable definitions should be initialized, and assignment operators should maintain consistent indentation. The initialized variable should be before the variable is initialized.
Good spelling
var count = ten,
name = "Jeri",
found = False,
empty;
function declaration
Functions should be defined in advance of use. A function that is not a method (that is, a property that is not an object) should use the format defined by the function (not the function expression and functions constructor format). There should be no spaces between the function name and the opening parenthesis. A space should be left between the closing parentheses and the curly braces on the right. The curly braces on the right should remain on the same line as the function keyword. There should be no spaces between the opening and closing parentheses. You should leave a space between the names of the parameters after the comma. The function body should maintain a level of indentation.
Good spelling
function outer () {
var count = ten,
name = "Jeri",
found = False,
empty;
function inner () {
//code
}
//Calling inner () code
}
An anonymous function may be assigned to an object as a method, or as an argument to another function. There should be no space between the function keyword and the opening parenthesis.
Good writing
Object.Method = function () {
//code
};
Bad wording: Incorrect space
Object.Method = function () {
//code
};
Functions that are called immediately should be wrapped in parentheses around the outer layer of the function call.
Good method
var value = (function () {
//Functional body return
{message
: "Hi"
}
} ());
Strict mode
Strict mode should be used only within functions, and should not be used globally.
Bad writing: The global use of strict mode
"using strict";
function dosomething () {
//code
}
//good spelling
function dosomething () {
"use strict";
Code
}
10. Operator
assigning values
When assigning to a variable, if the right side is an expression that contains a comparison statement, enclose the parentheses.
Good spelling
var flag = (I < count);
Bad writing: missing parentheses
var flag = i < count;
equals operator
Use = = = (strictly equal) and!== (strictly unequal) instead of = = (equality) and!= (unequal) to avoid weak type conversion errors.
Good writing
var same = (A = = = b);
Good writing
var same = (A = = B);
Ternary operator
Ternary operators should be used only in conditional assignment statements and not as substitutes for if statements.
Good writing
var value = condition value1:value2;
Bad writing: No assignment, should use the IF expression
condition? DoSomething (): Dosomethingelse;
11. Statement
Simple statement
Each row contains at most one statement. All simple statements should end with a semicolon (;).
A good writing
count++;
A = b;
Bad writing: Multiple expressions written in a row of
count++ a = b;
Return statement
The return statement should not use parentheses when returning a value, unless in some cases this makes it easier to understand the return values. For example:
return;
return Collection.size ();
return (Size > 0 size:defaultsize);
Compound statement
A compound statement is a list of statements enclosed in braces.
• The enclosed statement should be indented one level more than the compound statement.
• The opening brace should be at the end of the line where the compound statement is located, and the closing curly braces should be exclusive and have the same indentation as the beginning of the compound statement.
• When a statement is part of a control structure, such as an if or a for statement, all statements need to be enclosed in braces and include a single statement. This convention makes it easier for us to add statements without having to worry about forgetting braces and causing bugs.
• A keyword that starts with a statement like if, followed by a space, and the opening brace should be after a space.
If statement
The IF statement should be in the following format.
if (condition) {
Statements
}
if (condition) {
Statements
} else {
statements
}
if ( Condition) {
Statements
} else if (condition) {
Statements
} else {
statements
}
Omitting curly braces in an If statement is never allowed.
A good spelling
if (condition) {
dosomething ()
}
Bad wording: Improper space
if (condition) {
dosomething ();
}
Bad writing: All code is in line
if (condition) {dosomething ();}
Bad writing: All code is on one line and there is no curly brace
if (condition) dosomething ();
For statement
Statements for type should be in the following format.
For (initialization, condition update) {
statements
} for
(variable in object) {
statements
}
The initialization portion of the For statement should not have a variable declaration.
Good method
var i,
Len;
For (i=0, len=0 i < Len; i++) {
//code
}
//bad writing: declaring variable for
(Var i=0, len=0; i < Len; i++) {
//Code
}
//Bad writing: Declare variable for
(var prop in object) {
//code
} at initialization time
When using the For-in statement, remember to use hasOwnProperty () for double checking to filter the members of the object.
While statement
The statement of the while class should be the following format.
while (condition) {
Statements
}
Do statement
The statement of the Do class should be the following format.
Do {
statements
} while (condition);
Switch statement
The statement for the switch class should be the following format.
switch (expression) {case
expression:
statements
default:
statements
}
The first case under switch should be kept in one indent. Each case, except the first one, including default, should be preceded by a blank line.
Each set of statements (except default) should end with a break, a return, a throw, or a row of comments to skip.
Good wording
switch (value) {case
1:/
* falls through
/Case 2:
dosomething ();
break;
Case 3: Return
true;
Default:
throw new Error ("Some error");
}
If a switch statement does not contain a default condition, you should replace it with a line of comments.
Good wording
switch (value) {case
1:/
* falls through
/Case 2:
dosomething ();
break;
Case 3: Return
true;
Default:
//no default
}
Try Statement
The statement of the try class should be formatted as follows.
try {
statements
} catch (variable) {
statements
}
try {
statements
} catch ( Variable) {
statements
} finally {
statements
}
12. White leaves
Adding a blank line of code between logically related code can improve the readability of your code.
Two lines of blank lines are limited to:
• Between different source code files.
• Between class and interface definitions.
A single line of blank lines is used only in the following situations.
• between methods.
• Between the local variable and the first line statement in the method.
• Before multiple lines or single-line comments.
• The logical blocks of code in the method to improve the readability of the code.
Spaces should be used in the following situations.
• Keywords followed by parentheses should be separated by a space.
• You should leave a space after the comma in the argument list.
• All except the point (.) , the operands of the two-dollar operator should be separated by a space. The operands of the monocular operator should not be separated by whitespace, such as a unary minus sign, incrementing (+ +), and descending (-).
The expression of a for statement should be separated by a space.
13. The need to avoid
• Never create a new object using the original wrapper type like string.
• Avoid using eval ().
• Avoid using the WITH statement. The statement no longer exists in strict mode and may be removed in future ECMAScript standards.
Written in the last
These guidelines are not necessarily fully adhered to in the development process, and we can only learn a few of them to improve our coding style and make our code easy to read and maintain. On the coding style, each team has its own characteristics, as long as the consistency of the team, can be efficient development on the OK. Some of the rules are not what we have to abide by, for example, in the indentation aspect, we use the TAB key many times more convenient, but we cannot guarantee in any environment tab all represents 4 spaces, in order to maintain the consistency in the indentation aspect, if uses the TAB key then to use in the whole process; "and" use, we also do not have to use "", use "" is also possible, as long as the same style can be maintained. There are many other similar style problems, all by personal choice.
There is no absolute criterion, only appropriate.