1. Indent
Using a unified indentation style is important, and proper indentation can improve the readability of your code.
(1) Indent with tabs
Each indentation level is represented by a separate tab (tab character), one indent level is a tab, and two indent levels are two tab characters. The advantage is that the tab and indent levels are a one-to-many relationship, and most text editors can configure the display length of tabs. The downside is that different systems and different editors do not have the same explanation for tab characters.
(2) indent with a space
Three specific practices: 2 spaces, 4 spaces, and 8 empty glyd represent an indentation. 4 spaces to identify an indent is a more eclectic choice, and the advantage of using a space indent is that there is no difference in the format of the text presentation in all systems and editors.
Choosing tabs or spaces to indent is just a personal preference, but don't mix it up, which can make the file poorly formatted and requires a lot of cleanup work.
2. End of statement
Depending on the parser's automatic semicolon insertion (Automatic semicolon insertio, ASI) mechanism, the JavaScript code omits the semicolon to work correctly. In most scenarios, the ASI will correctly insert semicolons, but the semicolon insertion rules of ASI are complex and difficult to remember, so it is recommended not to omit semicolons. Douglas Crockford The programming specifications for JavaScript (hereinafter collectively referred to as Crockford programming specifications) recommend always using semicolons, likewise, the jquery Core style guide, Google's JavaScript style guide and the Dojo Programming style guide all recommend that you do not omit semicolons.
3. Length of the line
The length of the line is seldom mentioned in the JavaScript style guide, but the length of the specified line in the Crockford code specification is 80 characters.
4. Line break
When the line length reaches the limit of one-line maximum characters, you need to manually split a row into two lines. Usually wraps after the operator, and the next line increments by two levels of indentation.
// Good Practice: Wrap the operator after it, and append two indents to the second line; true , 123, navigator); // Bad Practice: The second line has only one indent true , 123, navigator); // Bad practice: line up before the operator true ,123, navigator);
When assigning a value to a variable, the position of the second row should remain aligned with the position of the assignment operator. Like what:
var result = something + anotherting + somethingelse + anothersomethingelse;
5. Blank Line
In general, the code should look like a series of readable paragraphs, rather than a large piece of continuous text that is rubbed together. Sometimes the semantics of a piece of code are irrelevant to another piece of code, and you should split them with empty lines to make sure that the code associated with the semantics is presented together.
if (Status = = 1) {for (var i = 0, Len = result.length;i < Len; i++) {= Result[i]; if (Obj.id = = = 1) { console.log ("Yse"); Else { Console.log ("no"); }}}
In general, it's a good idea to add empty lines in the scenario below.
(1) between the methods.
(2) between the local variable (local variable) and the first statement in the method.
(3) before a multiline or single-line comment.
(4) Insert a blank line between logical fragments within a method to improve readability.
But none of the programming specifications gives any concrete advice on the use of blank lines, and the Crockford programming specification only mentions using blank lines sparingly.
1.6 Naming
As long as the code is written, variables and functions are involved, so variable and function naming is critical to enhancing code readability. The core of the JavaScript language is ECMAScript, which is followed by the camel case naming method. Camel case The naming method starts with lowercase characters, and the first letter of each subsequent word is capitalized.
var Thisismyname; var anothervariable;
1.6.1 Variables and functions
Variable names should always obey Camel-case naming, and naming prefixes should be nouns. The prefix of a position allows a variable to be distinguished from a function, since the prefix of the functional name should be a verb.
//good wording.varCount = 10;varMyName = "haha";varFound =true;//bad notation: variables look like functionsvarGetCount = 10;varIsfound =true;//good wording.functionGetName () {returnMyName;}//bad notation: functions look like variablesfunctionthename () {returnMyName;}
The named length should be as short as possible and hold the focus. Try to reflect the data type of the value in the variable name. For example, naming count, length, and size indicates that the data type is a number, whereas naming name, title, and message indicates that the data type is a string. But variables named with a single character, such as I, J, and K, are usually used in loops. Using these names to represent data types makes it easy for your code to be read by others and yourself.
To avoid meaningless naming. Names such as Foo, bar, and TMP should also be avoided, but there are a lot of them in the Developer toolkit that can be used with the accompanying name, but don't let the names carry additional meanings.
For functions and method names, the first word should be a verb, and here are some common conventions for using verbs.
Verb |
Meaning |
Can |
function returns a Boolean value |
Has |
function returns a Boolean value |
Is |
function returns a Boolean value |
Get |
function returns a non-Boolean value |
Set |
function to hold a value |
1.6.2 Constants
Before ECMASCRIPT6, there was no real concept of constants in JavaScript. A common naming convention arises in order to differentiate between common variables (variable values are mutable) and constants (constants are not changed after initialization). This convention is derived from the C language, which uses uppercase letters and underscores to name and underline words.
1.6.3 constructor function
In JavaScript, a constructor is simply a function prefixed with the new operator, which is used to create an object. As with other naming conventions, the naming style of constructors is also consistent with the native language (Native Language), so the constructors are named according to the large Hump naming method (Pascal case). Both Pascal and Camel case denote "hump-cased", and the difference is that Pascal is starting with an uppercase letter. In doing so, you can distinguish a constructor from a variable and a normal function. Constructors are often named as nouns, because they are used to create instances of a type.
1.7 Direct Volume
JavaScript contains primitive values for some types: string, number, Boolean, NULL, and undefined. Similarly, it also contains the direct amount of the object and the direct amount of the array. Of these, only the Boolean self-explanatory (self-explanatory), the other types more or less need to think about how they can be more accurately expressed.
1.7.1 string
In JavaScript, strings are unique. Strings can be enclosed in double quotation marks or enclosed in single quotes. Unlike Java and PHP, strings enclosed in single and double quotes are functionally not different. The two approaches are fully functional, except that they need to be escaped in case of internal string qualifiers.
There is another question about strings that you need to be aware of, which is creating multiline strings. This feature does not come from the JavaScript language itself, but works in almost all (JavaScript) engines.
// bad wording. var longstring = "Here's the story, of a man named Haha.";
Although technically this is an illegal JavaScript syntax, it is true that you can create multiple lines of string in your code. This is not usually recommended because it is a artifice rather than a language feature and is explicitly forbidden in Google's JavaScript style guide. An alternative to multi-line strings is to use string connectors (+) to divide a string into multiple copies.
// good wording. var longstring = "Here's the story, of a man" + "named haha.";
1.7.2 Digital
There is only one type of number in JavaScript, because all numeric forms-integers and floating-point numbers-are stored as the same data type. There are other digital direct volume formats that represent different data formats.
//integervarCount = 10;//decimalvarPrice = 10.0;varPrice = 10.00;//non-recommended decimal notation: no fractional partvarPrice = 10.;//non-recommended decimal notation, no integer partvarPrice =. 1;//The octal system has been deprecated, not recommended .varnum = 010;//hexadecimal notationvarnum = 0xa2;//Scientific Counting Methodvarnum = 1e23;
The notation for octal numbers. JavaScript has long supported the notation of octal numbers as a source of many errors and ambiguities. The digital direct volume 010 does not represent 10, but rather represents 8 in octal. Most developers are not familiar with the octal format and are seldom used, so it is best to disallow octal direct in the code.
1.7.3 NULL
Null should be used in the following scenarios.
(1) to initialize a variable, the variable may be assigned to an object.
(2) To compare with an already initialized variable, this variable can or may not be an object.
(3) When a function parameter is expected to be an object, it is passed as a parameter.
(4) When the return value of a function is an object, it is used as the return value for outgoing.
There are some scenarios where null should not be used
(1) Do not use NULL to detect whether a parameter is passed in.
(2) Do not use NULL to detect an uninitialized variable.
//good usage.varperson =NULL;//good usage.functionGetperson () {if(condition) {return NewPerson ("haha"); } Else { return NULL; }}//good usage.varperson =Getperson ();if(Person!==NULL) {dosomething ();}//bad notation: used to compare with uninitialized variablesvarPerson ;if(Person!==NULL) {dosomething ();}//Bad writing: detect if a parameter is passed infunctiondosomething (arg1, arg2, Arg3, Arg4) {if(Arg4!==NULL) {dosomething (); }}
The best way to understand null is to treat it as a placeholder for the object (placeholder). This rule is not mentioned in all mainstream programming specifications, but is critical for global maintainability.
1.7.4 undefined
Undefined is a special value, then the variable that has not been initialized has an initial value, that is, undefined, which indicates that the variable waits for the value to be assigned.
// bad wording. var //true
Although this code works correctly, this value is often confused with the typeof operator that returns "undefined". In fact, the behavior of TypeOf is confusing, because whether the value is a undefined variable or an undeclared variable, the result of the TypeOf operation is "undefined".
By prohibiting the use of special value undefined, it is effective to ensure that TypeOf returns "undefined" only in one case: when the variable is not declared. If you use a variable that might (or might not) be assigned to an object, assign it a value of NULL.
// good practice. var NULL null//true
Assigning the initial value of a variable to NULL indicates the intent of the variable, and it is likely that it will eventually be assigned to an object. The TypeOf operator returns "Object" when the null type is used, so that it can be distinguished from the undefined.
1.7.5 Object Direct Volume
One of the most popular ways to create objects is to use the direct amount of the object to write out all the attributes directly in the direct volume, which can replace the practice of creating an instance of object first and then adding properties. When you define the direct amount of an object, you often include the left curly brace in the first row, a single row for each property's name-value pair, and a indentation, and the closing curly brace also holds a single line. Google's JavaScript style guide is highly recommended, and the Crockford programming specification also recommends using the direct amount instead of the object constructor, but does not give a specific writing format.
// bad wording. var New = "maintainable JavaScript"= "Nicholas C. Zakas"; // good wording. var book = { "maintainable JavaScript", "Nicholas C. Zakas"};
1.7.6 Array Direct Volume
Similar to the object's direct volume, the array direct amount is a way of defining the array in JavaScript. Do not approve the display to use the array constructor to create arrays. You can use two square brackets to enclose an array's initial elements in lieu of using the array constructor to create an array. This is recommended by Google's JavaScript style guide and Crockford programming specifications.
// bad wording. var New Array ("Red", "yellow", "blue"); var New Array (1, 2, 3, 4); // good wording. var colors = ["Red", "yellow", "blue"]; var numbers = [1, 2, 3, 4];
First, the basic formatting