Javascript programming style
Douglas Crockford is a Javascript authority, and the Json format is his invention.
In November last year, he had a speech ( Youtube ) about what is a good Javascript programming style.
I highly recommend this lecture. It not only helps to learn Javascript, but also makes you feel comfortable, because Crockford speaks very humorously and makes the audience smile from time to time.
Below, I will summarize the “Javascript programming style” based on this speech and the code specifications written by Crockford .
The so-called “programming style” refers to the style rules for writing code. Different programmers often have different programming styles.
Some people say that the compiler’s specification is called “grammar”, which must be followed by programmers; and the part that the compiler ignores is called “programming style”, which is free for programmers to choose. . This statement is not entirely correct. Programmers are free to choose a programming style, but a good programming style helps to write programs with higher quality, fewer errors, and easier maintenance.
Therefore, it should be clear that the choice of “programming style” should not be based on personal hobbies, familiarity, typing workload and other factors, but should consider how to make the code as clear and readable as possible and reduce errors. What you choose is not a style you like, but a style that can clearly express your intentions. This is especially important for languages such as Javascript, which have a high degree of grammatical freedom and are not fully mature in design .
First, the position of the braces
In most programming languages, braces ({}) are used to denote blocks. There are many different ways of writing the position of the opening brace .
There are two most popular. One is to start the brace on a new line:
block
{
…
}
The other is the opening brace following the keyword:
block {
…
}
Generally speaking, both writing methods are acceptable. However, Javascript should use the latter, because Javascript will automatically add a semicolon at the end of the sentence, causing some undetectable errors.
return
{
key:value;
};
The original intention of the above code is to return an object, but in fact it returns undefined, because Javascript automatically adds a semicolon after the return statement. In order to avoid this type of error, it needs to be written as follows:
return {
key: value;
};
therefore,
Rule 1: The brace at the beginning of the block, do not start a new line.
Two, parentheses
Parentheses have two functions in Javascript, one means calling a function, and the other means grouping of different values. We can use spaces to distinguish 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 grammatical elements and the opening parenthesis.
According to the above rules, the following writing is not standardized:
foo (bar)
return(a+b);
if(a === 0) {…}
function foo (b) {…}
function(x) {…}
Three, semicolon
The semicolon indicates the end of the statement. In most cases, if you omit the semicolon at the end of the sentence, Javascript will be added automatically.
var a = 1
Equivalent to
var a = 1;
Therefore, some people advocate omitting the semicolon at the end of the sentence. But the trouble is that if the first character (token) of the next line is one of the following five characters, Javascript will not add a semicolon to the end of the sentence on the previous line : “(“, “[“, “/”, ” +” and “-“.
x = y
(function (){
…
})();
The above code is equivalent to
x = y(function (){…})();
therefore,
Rule 5: Don’t omit the semicolon at the end of the sentence.
Four, with statement
with can reduce the writing of the code, but it will cause confusion.
with (o) {
foo = bar;
}
The above code can have four running results:
o.foo = bar;
o.foo = o.bar;
foo = bar;
foo = o.bar;
These four results may occur, depending on whether the different variables are defined. therefore,
Rule 6: Do not use the with statement.
Five, equality and strict equality
Javascript has two operators for “equal”: “equal” (==) and “strictly equal” (===).
Because the “equal” operator will automatically convert variable types, causing 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
therefore,
Rule 7: Do not use the “equal” (==) operator, only use the “strictly equal” (===) operator.
Six, the combination of sentences
Some programmers pursue brevity and like to combine statements for different purposes. For example, the original sentence is
a = b;
if (a) {…}
He likes to write it like this:
if (a = b) {…}
Although the statement is missing a line, its readability is greatly reduced, and it will cause misunderstandings, making others mistakenly believe that this line of code means:
if (a === b){…}
Another situation is that some programmers like to assign multiple variables on the same line:
var a = b = 0;
He thought that this line of code is equivalent to
var a = 0, b = 0;
Actually not, its real effect is as follows:
b = 0;
var a = b;
therefore,
Rule 8: Do not combine statements with different purposes into one line.
Seven, variable declaration
Javascript will automatically “hoist” the variable declaration to the head of the block.
if (!o) {
var o = {};
}
Equivalent to
var o;
if (!o) {
o = {};
}
In order to avoid possible problems, it is better to put variable declarations at the head of the code block.
for (var i …) {…}
It’s best to write:
var i;
for (i …) {…,}
therefore,
Rule 9: All variable declarations are placed at the head of the function.
Rule 10: All functions are defined before they are used.
Eight, global variables
The biggest grammatical disadvantage of Javascript may be that global variables are readable and writable for any code block. This is very detrimental to the modularization and reuse of the code.
Rule 11: Avoid using global variables; if you have to use them, use capital letters to indicate variable names, such as UPPER_CASE.
Nine, 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, the this keyword inside myObject() will point to the global object, causing all variables bound to this to become all variables.
Rule 12: Do not use the new command, use the Object.create() command instead .
If you have to use new, in order to prevent errors, it is best to visually distinguish the constructor from other functions.
Rule 13: The name of the constructor function should be capitalized (InitialCap); for other function names, the first letter should be lowercase.
Ten, increment and decrement operators
Increment (++) and decrement (–) operators, placed before or after the variable, return different values, which is prone to errors.
In fact, all ++ operators can be replaced with “+= 1”.
++x
Equivalent to
x += 1;
The code becomes clearer. There is a ridiculous example, the following snippet appeared in the source code of a certain Javascript library:
++x;
++x;
This programmer forgot, there is a simpler and more reasonable way of writing:
x += 2;
therefore,
Rule 14: Do not use the increment (++) and decrement (–) operators, use += and -= instead.
11. Block
If the code body of the loop and judgment is only one line, Javascript allows the block to omit the braces.
The code below
if (a) b(); c();
The original intention may be
if (a) {b(); c();}
However, the actual effect is
if (a) {b();} c();
therefore,
Rule 15: Always use braces to denote blocks.
(over)