Some JavaScript coding specifications

Source: Internet
Author: User
Tags coding standards uppercase letter

For Engineers familiar with the C/C ++ or Java language, JavaScript is flexible, easy to understand, and requires relatively loose code formats. It is easy to learn and use it in your own code. Because of this, JavaScript coding standards are often despised. Fixing and complementing during the development process will eventually become a nightmare for subsequent maintenance personnel. The long-term value of software is directly proportional to the coding quality. Coding specifications can help us reduce unnecessary troubles in programming. While JavaScript code is directly sent to the client's browser and directly met with the customer, the quality of code should be paid more attention.

This article describes the coding standards in JavaScript programming and analyzes the reasons. It is expected that more Web developers will pay attention to JavaScript coding standards and software product quality issues.

I believe many engineers are not unfamiliar with the C/C ++ and Java coding specifications. However, when it comes to the JavaScript language encoding specifications, you may not be able to help. Isn't JavaScript syntax flexible? Variables can be declared at any time; statement Terminator can be avoided; string and number can also be added; one or more parameters will not report an error. Yes, when you switch from the strict C/C ++ and Java syntax rules to the JavaScript language, you will feel a lot of freedom and much easier. Loose syntax is an important feature of JavaScript. It is flexible and easy to understand, and brings a lot of convenience to developers. However, if you do not pay attention to the coding process, the debugging and maintenance costs of the code will be invisible.

JavaScript code will be directly sent to the browser on the client as needed. The code specification not only guarantees the code quality, but also affects the long-term reputation of the product. We hope that the standardization of the JavaScript programming language will also attract more attention from friends.

This article provides some suggestions for the formatting, naming, declaration, scope, and use of some special symbols involved in the JavaScript coding process, and analyze the reason for reference.

JavaScript file reference

JavaScript programs should be stored in. js files as much as possible and included in HTML in the form of <script src = "filename. js"> when called. If JavaScript code is not specific to the HTML file, avoid writing JavaScript code directly in the HTML file. This will greatly increase the size of HTML files and will not help code compression and Cache Usage.

In addition, the <script src = "filename. js"> label should be placed behind the file as much as possible. This reduces the loading time of other components on the page due to loading JavaScript code.

Code Layout

Row Length

Each line of code should be less than 80 characters. If the code is long, use line breaks as much as possible. The next line of code should be indented with 8 spaces. In this way, the code can be neatly formatted to reduce the fatigue of reading the code. Line feed indentation 8 spaces can be separated from the code segment indentation 4 spaces to enhance the readability of the Code.

Row end

The JavaScript statement should end with a semicolon. However, most browsers do not allow writing a semicolon, as long as there is a line break in the place where it should be a semicolon. But what are precautions for long lines of code that require line breaks? The line feed should be after the operator and punctuation, preferably after the comma ',', instead of the variable name, String, number, or ') '']'' + ''-- 'and then wrap the line.

This effectively prevents errors caused by copying and pasting, and effectively enhances the readability of the Code. See Listing 1. The code output meets our expectations. However, in terms of writing, the valueB value assignment statement is a line break after the valueA variable, which is easily misunderstood as valueB = ValueA, leading to reading barriers. The copy statement for valueC is a line break after '+', which is much easier to understand. This is also the line feed method advocated in this article.

Listing 1. End position of a row

<script language="javascript"> var valueA = 1; var valueB = valueA ///bad +1; var valueC = valueB +  ///good valueA; alert(valueB);        //output: valueB=2 alert(valueC);//output: valueC=3 </script> 

Indent

Indentation is not just JavaScript. It is mentioned in almost all languages. Indentation is the first lesson in code writing standards, and is a direct factor in code readability judgment.

The benefits of code indentation are self-evident, but there is no standard for how to indent. The most popular feature is the ease of using the TAB key indent, and some prefer to use two, four, and eight spaces for indentation. In this way, the indentation style is different, which also brings obstacles to code reading.

This article advocates four spaces for indentation, and the same indentation standard is adopted in the same product. TAB-based indentation is not supported. This is because up to now there is no uniform standard to define the blank size replaced by the TAB key. Some editors resolve the size to four spaces, and some to eight. Therefore, using different editors to view code may cause format confusion. Of course, TAB is easy to use. To solve this problem, we recommend that you reset the TAB shortcut key in the editor to four spaces when setting the development environment. It is understood that Eclipse, Vi, Nodepad ++, Editplus, UltraEdit and other popular editors provide this function.

Note

Comments in the Code are important and naturally beyond all doubt. Generally, we emphasize the number of comments in the Code, while ignoring the improvement of the annotation quality. Encoding is to add comments in a timely manner, which will bring great convenience to the maintenance personnel of the subsequent code. However, if the comments do not pay attention to updates, or the comments are incorrect due to copying or pasting, the readers will be misled, which in turn brings obstacles to reading.

In addition to timely updating comments, we should pay special attention to the comments. Annotations should be as simple and clear as possible to avoid the use of obscure languages, and emphasize the meaning of annotations to annotate less intuitive parts. See list 2.

Listing 2. Meaningful comments

<script language="javascript"> //following section is used to initialize golbal variables             (good) var valueA = 0;     //initialize  valueA to be sero                       (bad) var valueB = 1; ... //call f1 function after waiting for 50 seconds.                         (good) setTimeout(f1,50000); //set timeout to be 20s                     (copy error) ... </script> 

This annotation method is often seen in JavaScript code. What is the use of comments like "initialize valueA to be sero? Can't the engineer who reads the program find out from the "var valueA = 0;" copy statement? "Set timeout to be 20 s" is not only a copy or paste error, but also misleading the programmer's understanding of this statement. The setTimeout () function is not used to set the function execution timeout, but to wait for a certain amount of time before executing the called function. Such comments would rather be deleted.

In addition, there are two types of JavaScript Annotations: "//" and "/*.... */", it is recommended that" // "be used as a code line comment ,"/*.... */"is used to deregister the entire code segment, or to describe the function parameters, functions, and file functions in a more formal declaration.

Identifier name

Naming rules for identifiers in JavaScript:

  • It must start with a letter, underscore '_', or dollar sign '$ '.
  • The name can contain letters, numbers, underscores '_', and dollar signs '$'
  • Case Sensitive

The names of variables, parameters, member variables, and functions all start with lowercase letters, and the name of the constructor starts with an uppercase letter. Variables starting with underscore '_' are generally used to identify private/local members. Variables starting with the dollar sign '$' are used to identify system-related variables, such as system processes. Do not use the underscore '_' or dollar sign '$' to name the identifier. Reduce the burden of reading code as much as possible.

Statement

Variable Declaration

Although JavaScript does not require that variables be declared before they are used. But we should develop this good habit. In this way, we can easily detect undeclared variables to avoid hidden global variables and cause potential risks.

At the beginning of a function, you should first use the var keyword to declare the local variables to be used in the function, comment out the functions and meanings of the variables, and sort them alphabetically. Each variable occupies a single row to add comments. This is because only the {} of the function indicates the scope in JavaScript. The local variables declared with the var keyword are valid only in the function, while those declared without var are considered as global variables. Let's take a look at listing 3.

Listing 3. Local variable Declaration

<script language="javascript"> var valueA  = "a"; var valueB  = "b"; function f1() { var valueA = "c";    alert("valueA="+valueA);        //output: valueA=c    valueB = "d";    alert("valueB="+valueB);        //output: valueB=d } f1(); alert("valueA="+valueA);            //output: valueA=a alert("valueB="+valueB);            //output: valueB=d </script> 

From the above output, we were surprised to find that the valueA variable declared with var is different from the valueB variable without declaration. Note that the variables declared by var in the function are local variables, which can effectively avoid errors caused by the same name of local variables and global variables.

Function Declaration

The function should also be declared before calling. The internal function should be declared after the var statement declares the internal variable, which can clearly indicate the scope of the internal variable and the internal function.

In addition, there must be a space between the function name '(') 'and, to clearly display the function name with its parameter section, and the start of the function body. If the function is an anonymous or untitled function, leave a space between the function keyword and the left brace '('; otherwise, the function name may be mistaken.

Listing 4. Internal function declaration

<script language="javascript"> var innerA = 1; function outF() { var innerA = 2;    function _inF() {        alert("valueA="+innerA);    }    _inF(); } outF();                         //output: valueA=2 _inF();                         //error: innerF is not defined </script> 

From the output in Listing 4, we can see that the inF () function takes effect only within the outF () function, and the innerA local variable takes effect for the scope of the internal function. This encoding method makes the scope of variables and functions clearer.

Statement

For a simple statement, we need to mention the necessity of a semicolon. At the same time, a maximum of one statement can be entered in a row. If a value assignment statement uses functions and objects to assign values, it may need to be performed across multiple rows. Be sure to add a semicolon at the end of the value assignment statement.

This is because in JavaScript, all expressions can be used as statements. In case of line breaks, it will be resolved to the end of the expression. In this case, nonstandard line breaks and the loss of semicolons may lead to new errors.

For compound statements, if, for, while, do, switch, try... Catch and other code bodies, function-defined function bodies, and object definitions must be placed in curly brackets.

  • '{' Indicates the beginning of the code block at the end of the line.
  • '}' Should start with a line, marking the end of the code block. It must be aligned with the start of the row where '{' is located to indicate a complete compound statement segment. This greatly improves the readability of the code, and the control logic can be clearly displayed.
  • The included code segment should be indented with four spaces.
  • Even if the included code segment contains only one sentence, it should be included in braces. Although no curly braces are required, compilation errors or logical errors may be caused by the omission of curly braces if you need to add statements.

The return statement must also be used with caution. If the expression execution is used as the return value, put the expression and return in the same line to avoid the return error caused by the end of the statement. If no expression is returned after the return keyword, undefined is returned. The default return value of the constructor is this.

Listing 5. return expression

<script language="javascript"> function F1() { var valueA  = 1;    var valueB  = 2;    return valueA + valueB; } function F2() {    var valueA  = 1;    var valueB  = 2;    return        valueA + valueB; } alert( F1() );  //output: 3 alert( F2() );  //ouput: undefined </script> 

Listing 5 shows the returned error because the return expression is not in the same line as the return keyword.

Special symbols

Blank Space Character

Appropriate blank lines can greatly improve the readability of the Code and make the code logic clearer and easier to understand. At the same time, leaving the appropriate blank in the expression will also facilitate the reading of the Code.

If there are Parentheses behind the keyword, it is best to leave a blank between the keyword and the left brace '(', such as for, if, while, etc. The function name and brackets should not be left blank, but if it is an anonymous function, it must be left blank between the function and left brace ('). Otherwise, the editor will mistakenly think that the function name is function.

In an expression, it is best to leave a blank space between the binary operator (except the left brace '(', left brace '[', scope point '.') and the two operands. Do not leave a blank space between the unary operator (if not the word typeof) and Its operands.

The comma ',' must be left blank to display the specified parameter interval and variable interval.

The semicolon ';' usually indicates the end of the expression statement, but should be empty. In the for Condition Statement, leave blank after the semicolon.

{} And []

In JavaScript, if empty objects and empty arrays need to be defined, the new Object () and new Array () methods are naturally used. In fact, braces '{}' and square brackets '[]' can be directly used to define an empty object and an empty array. This writing method makes the code easy to understand.

==And ===

Determining "logic and so on" is too common in code, but JavaScript is different from other well-known programming languages, in addition to using two equal signs '=' for judgment, you can also use three equal signs '=' for logical judgment. The difference between the two is that when '=' is used for logic judgment, type conversion is performed before comparison. '=. Therefore, the result of '=' may be biased. '! = 'And '! =. This article advocates using '=' as much as possible for logical judgment '! =.

LIST 6. =

<script language="javascript"> var valueA = "1"; var valueB = 1; if ( valueA == valueB) {    alert("Equal"); } else {    alert("Not equal") } //output: "Equal"if ( valueA === valueB) {    alert("Equal"); } else {    alert("Not equal") } //output: "Not equal"</script> 

In Listing 6, the values of valueA and valueB are obviously not equal. At least valueA is a string, while valueB is a number. However, if '=' is used for determination, the program outputs equal words. This is because the compiler automatically converts valueB to a string and compares it with valueA when comparing two variables because of their different types. The result obtained with '=' is consistent with the expected result.

+

The plus sign '+' is also one of the operators familiar to programmers. JavaScript is different from other programming languages. In JavaScript, '+' not only indicates the addition of numeric values, but also connects strings. It can also be used as an unary operator to convert strings into numbers. Therefore, improper use may be confused with the auto-incrementing character '+ +', resulting in a computing error. This can be clearly seen in listing 7.

Listing 7. Clever Use + number

<script language="javascript"> var valueA = 20; var valueB = "10"; alert( valueA + valueB);     //ouput: 2010 alert( valueA + (+valueB)); //output: 30 alert( valueA + +valueB);    //output:30 alert( valueA ++valueB);     //Compile error </script> 
Summary

This article describes the JavaScript code layout, naming, declaration, statements, and the use of some special characters. In addition, there are many aspects that require in-depth research, such as the use of with, eval statements, and this object. While recognizing its universality, we also need to pay attention to its particularity and pay more attention when writing code to create more and better program code.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.