Transfer from Nanyi http://www.ruanyifeng.com/blog/2012/04/javascript_programming_style.html
Nanyi
Date: April 27, 2012
Douglas Crockford is the JavaScript authority, and the JSON format is his invention.
Last November he had a speech (Youtube) about what a good JavaScript programming style was.
I highly recommend this speech, which not only helps to learn JavaScript, but also makes you feel comfortable because Crockford is very humorous and makes the audience smile from time to time.
Below, I summarize the "JavaScript programming style" according to the code specifications written by this lecture and Crockford.
The so-called "programming Style" (programming style) refers to the style rules for writing code. Different programmers tend to have different programming styles.
It is said that the compiler's specification is called "Grammar rules" (grammar), which is the programmer must obey, and the compiler ignores the part called "Programming Style" (programming style), this is the programmer is free to choose. While this is not entirely true, programmers are free to choose the programming style, but good programming styles help write programs that are more quality, less error-prone, and easier to maintain.
So, it should be clear that the choice of "programming style" should not be based on personal interests, familiarity, typing workload and other factors, but to consider how to make the code clear and easy to read and reduce errors. What you choose is not the style you like, but a style that clearly expresses your intentions. This is especially important for JavaScript, which has a high degree of grammatical freedom and is not fully developed.
The position of a curly brace
Most programming languages use curly braces ({}) to represent chunks. The position of the opening brace has many different formulations.
There are two of the most popular. One is the beginning of the curly brace another line:
Block
{
...
}
The other is the opening brace followed by the keyword:
Block {
...
}
Generally speaking, both of these formulations can be accepted. However, JavaScript uses the latter because JavaScript automatically adds a semicolon at the end of a sentence, causing some imperceptible errors.
Return
{
Key:value;
};
The original intent of the above code is to return an object, but it actually returns undefined, because JavaScript automatically adds a semicolon after the return statement. To avoid this type of error, you need to write the following:
return {
Key:value;
};
So
Rule 1: The curly brace that represents the beginning of the block, not another line.
Second, parentheses
Parentheses (parentheses) have two functions in JavaScript, one for calling a function and another for a combination of different values (grouping). We can use spaces to distinguish between these two different parentheses.
Rule 2: When calling a function, there is no space between the function name and the opening parenthesis.
Rule 3: There is no space between the function name and the parameter sequence.
Rule 4: There is a space between all other syntax elements and the opening parenthesis.
According to the above rules, the following wording is not standard:
Foo (BAR)
return (A+B);
if (a = = 0) {...}
function Foo (b) {...}
function (x) {...}
Third, semicolon
A semicolon indicates the end of the statement. In most cases, if you omit the semicolon at the end of the sentence, JavaScript is automatically added.
var a = 1
Equivalent to
var a = 1;
Therefore, it is advocated to omit the semicolon at the end of the sentence. But the trouble is, if the first character (token) of the next line is one of these five characters, JavaScript will not add a semicolon to the end of the previous line: "(", "[", "/", "+" and "-".)
x = y
(function () {
...
})();
The above code is equivalent to
x = y (function () {...}) ();
So
Rule 5: Do not omit the semicolon at the end of the sentence.
Iv. with statements
With can reduce the writing of code, but can cause confusion.
With (o) {
foo = bar;
}
The above code, can have four kinds of running results:
O.foo = bar;
O.foo = O.bar;
foo = bar;
foo = O.bar;
All four of these results can occur, depending on whether or not different variables are defined. So
Rule 6: Do not use the WITH statement.
Five, equal and strictly equal
JavaScript has two operators that represent equality: equality (= =) and strict equality (= = =).
Because the equality operator automatically converts variable types, it causes many unexpected situations:
0 = = "'//True
1 = = TRUE//True
2 = = TRUE//False
0 = = ' 0 '//True
False = = ' false '//False
false = = ' 0 '//True
"\t\r\n" = = 0//True
So
Rule 7: Do not use the equality (= =) operator, only the strict equality (= = =) operators.
Vi. merging of statements
Some programmers pursue brevity and prefer to combine statements of different purposes. For example, the original statement is
A = b;
if (a) {...}
He likes to write the following:
if (a = b) {...}
Although the statement is one line less, but the readability is greatly discounted, and can cause misreading, let others mistakenly think this line of code means:
if (a = = B) {...}
Another scenario is that some programmers prefer to assign multiple variables in the same row:
var a = b = 0;
He thought that this line of code was equivalent to
var a = 0, b = 0;
Actually not, its real effect is the following:
b = 0;
var a = b;
So
Rule 8: Do not combine statements of different purposes into one line.
Seven, variable declaration
JavaScript automatically declares the variable "lifted" (hoist) to the head of the code block (block).
if (!o) {
var o = {};
}
Equivalent to
var o;
if (!o) {
o = {};
}
To avoid a possible problem, put the variable declaration in the head of the code block.
for (var i ...) {...}
Best written:
var i;
for (I ...) {...,}
So
Rule 9: All variable declarations are placed on the head of the function.
Rule 10: All functions are defined before they are used.
VIII. Global Variables
The biggest grammatical disadvantage of JavaScript is that global variables are readable and writable for any block of code. This is very detrimental to the modular and repetitive use of code.
Rule 11: Avoid using global variables; If you have to, use uppercase letters to denote variable names, such as Upper_case.
Ix. new command
JavaScript uses the new command to generate a new object from the constructor.
var o = new MyObject ();
The problem with this approach is that once you forget to add New,myobject () The inside of the This keyword will point to the global object, causing all the variables bound on this to become all variables.
Rule 12: Do not use the new command instead of the object.create () command.
If you have to use new, it's a good idea to visually distinguish constructors from other functions in order to prevent errors.
Rule 13: The function name of the constructor, with the first letter capitalized (INITIALCAP), the other function name, all the first letter lowercase.
X. Self-increment and decrement operators
The increment (+ +) and decrement (-) operators, placed before or after a variable, return a different value and are prone to errors.
In fact, all the + + operators can be replaced with "+ = 1".
++x
Equivalent to
x + = 1;
The code becomes clearer. There is a ridiculous example where the following fragment appears in the source code of a JavaScript library:
++x;
++x;
The programmer forgot that there was a simpler and more reasonable notation:
x + = 2;
So
Rule 14: Do not use the self-increment (+ +) and decrement (-) operators, substituting + = and-=.
Xi. Block
If there is only one line in the loop and judging code body, JavaScript allows the block to omit the curly braces.
The following code
if (a) B (); C ();
The original intention may be
if (a) {B (); C ();}
However, the actual effect is
if (a) {B ();} c ();
So
Rule 15: Always use curly braces to represent chunks.
JavaScript programming Style