A brief talk on coding specification of JavaScript programming language-Basic knowledge

Source: Internet
Author: User
Tags uppercase letter
The JavaScript programming language, as the most popular client-side scripting language, has long been known to many WEB developers. With the advent of the Web2.0 era and the wide application of Ajax technology, JavaScript has gradually attracted more attention. The more you work on the JavaScript language, the more you use it flexibly, and the quality of your coding.

For engineers who are familiar with C + + or the Java language, JavaScript is flexible, easy to understand, and relatively loosely formatted for code. It's easy to learn and apply to your own code. Also because of this, JavaScript coding norms are often despised, the development process of tinkering, and eventually evolved into a follow-up maintenance personnel nightmare. The long-term value of software is directly proportional to the quality of the code. Coding specifications can help us reduce unnecessary trouble in programming. And JavaScript code is sent directly to the client browser, directly with the customer to meet, the quality of the coding should be more attention.

This paper discusses the problem of coding standard in JavaScript programming, and analyzes the reasons. Expect more WEB developers to focus on JavaScript coding specifications and focus on software PRODUCT quality issues.

Preface

It is believed that many engineers are not unfamiliar with the reference to C + + and Java coding specifications. But when it comes to coding specifications for JavaScript languages, you might be laughing. Isn't JavaScript a very flexible syntax? Variables can be declared at any time, the statement terminator can be not, strings and numbers can be added, and a few more arguments will not error. Yes, when you turn to JavaScript language from the strict syntax of C + + and Java, you will feel free and relaxed a lot. Loose grammar is an important feature of JavaScript. It is flexible and easy to understand, bringing a lot of convenience to developers, but if the writing process is not noticed, the debugging and maintenance costs of the code will increase invisibly.

JavaScript encoding should be sent directly to the client's browser, code specifications are not only the guarantee of code quality, but also affect the long-term reputation of the product. I hope that the specification of JavaScript programming language can also arouse the attention of more friends.

JavaScript Coding Specification Recommendations

In this paper, in terms of typesetting, naming, declaration, scope, and the use of some special symbols in JavaScript coding process, some suggestions are given according to the summary of individual learning work, and the reasons are analyzed.

JavaScript file References

JavaScript programs should be kept in a. js file, which should be included in HTML in the form of < script src= "Filename.js" > when called. If the JavaScript code is not specific to the HTML file, you should try to avoid writing JavaScript code directly in the HTML file. Because this will greatly increase the size of the HTML file, is not conducive to the compression of the code and the use of caching.

In addition, the <script src= "filename.js" > label should be placed behind the file as far as possible. This reduces the load time that affects other components in the page by loading JavaScript code.

Code layout

length of the President

Each line of code should be less than 80 characters. If the code is longer, you should try to select a newline, and the next line of code should indent 8 spaces. This allows the code to be neatly formatted to ease the fatigue of the reading code. A newline indent of 8 spaces can be separated from the indentation of the code snippet by 4 spaces to enhance the readability of the code.

End of Line

JavaScript statements should end with semicolons. But most browsers allow a semicolon to be written, as long as there is a line break in place where the semicolon should be. But if the code line is longer and needs to be wrapped, what are the considerations? line breaks should be followed by the operator and punctuation, preferably after the comma ', ' and not after the variable name, string, number, or ' ' + + '-' + + '-' symbol.

This can effectively prevent copying, pasting and errors caused by, and can effectively enhance the readability of the code. See Listing 1 for the output of the code that meets our expectations. But in terms of writing, the assignment statement for VALUEB is the line of change after the variable Valuea, which can easily be misinterpreted as Valueb=valuea, causing obstacles to reading. And for the VALUEC copy statement is in the ' + ' after the line, it is easy to understand more. This is also advocated in this article the line-wrapping way.

Listing 1. Where the line ends

Code:
 code as follows:

<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

The problem with indentation, not just JavaScript, is that almost all languages are written with reference to indentation. Indentation is almost the first lesson of code coding, which is a direct factor in the judgment of code readability.

The benefits of code indentation are self-evident, but there is no standard for how to indent. The most popular is easy to use the TAB key indentation, but also some like to use 2, 4, 8 spaces for indentation. This indentation style is different, but also to the reading of the code to create obstacles.

This article advocates the use of 4 spaces for indentation and the same indentation standard in the same product. The TAB key is not supported for indentation. This is because until now there is no uniform standard to define the blank size that the TAB key replaces, some of the editors resolve to 4 space sizes, and some resolve to 8. Thus, viewing the code in a different editor can cause confusion in the format. Of course tab is easy to use, in order to solve this problem, it is recommended that when setting up the development environment, the Editor's tab shortcuts are reset to 4 spaces. It is understood that the popular editors such as Eclipse, Vi, Nodepad++,editplus, UltraEdit, etc., all provide this functionality.

Comments

The annotations in the code are important, and naturally there is no doubt about it. In general, we will emphasize the number of comments in the code, and despise the improvement of the annotation quality. Coding is a timely addition of annotations, which can be a great convenience to the maintenance of subsequent code. However, if the comments do not pay attention to the update, or because of the errors caused by the copy and paste, it will mislead the reader, but the reading is a barrier.

In addition to updating the annotations in a timely manner, we should pay special attention to the contents of the annotations. Note to be as simple and clear as possible, avoid ambiguous language, and emphasize the meaning of annotation, and annotate the less intuitive parts. Please see Listing 2.

Listing 2. Meaningful annotations

Code:
 code as follows:

<script language= "JavaScript" >
Following section are used to initialize Golbal variables (good)
var Valuea = 0; Initialize Valuea to is Sero (bad)
var valueb = 1;
...
Call F1 function after waiting for seconds. (good)
SetTimeout (f1,50000); Set timeout to is 20s (copy error)
...
</script>

Such annotations are often seen in JavaScript code. What's the use of annotations like "initialize Valuea to be Sero"? Does the reader program engineer from "var Valuea = 0;" Can't you see it in the copy statement? The "Set timeout to" 20s "annotation is not just an error in the amount of time caused by a copy or paste, but also misleading the programmer's understanding of the statement. The settimeout () function is not to set the timeout for function execution, but to wait a certain amount of time to execute the function called, the harm is shallow. Such annotation content would rather be deleted.

In addition, the JavaScript annotation has two kinds of "//" and "* .... * *", recommended "//" as line of code comments, "/* ... *" form for the entire code section of the cancellation, or more formal declarations, such as function parameters, functions, file functions, and other descriptions.

identifier naming

Naming rules for identifiers in JavaScript:

Start with the letter, underscore ' _ ' or dollar sign ' $ '

Allow names to contain letters, numbers, underscores ' _ ' and dollar sign ' $ '

Case sensitive

Names of variables, parameters, member variables, functions begin with lowercase letters, and the constructor's name begins with an uppercase letter. Variables that begin with the underscore ' _ ' are generally used to identify private/local members. The variable at the beginning of the dollar sign ' $ ' is used to identify system-related things, such as system processes. You should avoid naming identifiers with the underscore ' _ ' or dollar sign ' $ '. As much as possible to reduce the reading burden of the code.

Statement

Declaration of variables

Although the JavaScript language does not require the variable to be declared before it is used. But we should still develop this good habit. This makes it easier to detect those undeclared variables and avoid them from becoming hidden global variables, causing pitfalls.

At the beginning of the function you should declare the local variables to be used in the function with the Var keyword, annotate the function of the variable and the meaning of the representation, and it should be sorted alphabetically. Each variable occupies a single row in order to add a comment. This is because only the {} function in JavaScript indicates the scope, and local variables declared with the VAR keyword are valid only within the function, while variables declared without Var are treated as global variables. Let's take a look at listing 3.

Listing 3. Local variable declaration

Code:
 code as follows:

<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 output of the example above, it is surprising to find that the variable Valuea with the Var declaration is different from the VALUEB variable. It is particularly noteworthy that variables declared within functions with VAR are local variables, which effectively avoid errors caused by the same name as local variables and global variables.

Declaration of functions

The function should also be declared before the call, and the intrinsic function should be declared after the statement that the Var declares the internal variable, which clearly indicates the scope of the internal and internal functions.

In addition, the function name has a space between the opening parenthesis ' (between the ' and the right parenthesis ') and the ' {' behind ' {' to clearly show the function name with its parameter part, and the start of the function body. If the function is an anonymous/nameless function, then the function keyword and the left parenthesis ' (' between ') are blank, or you may mistakenly assume that the function is called a functions.

Listing 4. Internal function Declaration

Code:
 code as follows:

<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>

As you can see from the output in Listing 4, the InF () function takes effect only within the OUTF () function, and the local variable Innera the scope of the internal function. This encoding allows the scope of variables and functions to become clearer.

statement

For simple statements, it is still necessary to mention the semicolon necessity, while the line has at most one statement. If an assignment statement uses functions and objects to assign values, you may need to span multiple lines, and always remember to add a semicolon at the end of the assignment statement.

This is because in JavaScript, all expressions can be used as statements, and when line breaks are resolved to the end of an expression, a new error may be introduced when irregular wrapping and semicolons are lost.

For compound statements, if, for, while, do, switch, try ... catch and other code bodies, function-defined function bodies, object definitions, etc., need to be placed inside the curly braces ' {} '.

' {' should be at the end of the line, marking the beginning of the code block.

'} ' should be at the beginning of a line, marking the end of a block of code and needing to align with the beginning of the line ' {' to indicate a complete compound statement segment. This can greatly improve the readability of the code, control logic can be clearly demonstrated.

The included code snippet should be indented 4 more spaces.

Even if the included code snippet is only one sentence, it should be included with the curly brace ' {} '. It's not wrong to use curly braces, but if you need to add statements, it's easier to compile errors or logic errors due to missing curly braces.

The return statement is also prudent when used, and if the expression is executed as the returned value, put the expression and the returns in the same row so that the line break is incorrectly resolved to the end of the statement and cause a return error. Returns undefined if no expression is returned after the return keyword. The default return value for the constructor is this.

Listing 5. Return expression

Code:
code as follows:

<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>

In Listing 5, you need to pay attention to the return error caused by the return expression not being placed on the same line as the returned keyword.

Special Symbols

Blank character

The right blank line can greatly improve the readability of the code and make the code logic clearer and easier to understand. At the same time, the appropriate left blank in the expression, will also bring convenience to the code reading.

After the keyword is followed by parentheses, it is best to leave a blank between the keyword and the opening parenthesis ' (', for example, if, while, and so on. There is no space between the function name and the parentheses, but in the case of anonymous functions, you must leave blank between the function and the left parenthesis ' (', otherwise, the editor will mistakenly assume that it is called a functions.

In an expression, the two-dollar operator (except opening parenthesis ' (', left bracket ' [', Scope Point '. ') and two operands is best left blank. A unary operator (other than the word typeof) and its operands should not be left blank.

Comma ', ' after the need to leave blank to show clear parameter intervals, variable intervals, and so on.

Semicolon '; ' This usually indicates the end of the expression statement and should be blank. In the for conditional statement, the semicolon should be left blank.

{} and []

In JavaScript, if you want to define empty objects and empty arrays, it is often natural to think of the new object () and the new Array () method. In fact, the curly braces ' {} ' and the square brackets ' [] ' can be used directly to define an empty object and an empty array. This writing method makes the code look easy to understand.

= = and = =

Judging "logic, etc." in the code is too common but things, but JavaScript and other well-known programming language is different, in addition to the use of two equal equals ' = = ' to judge, you can also use the three equal sign ' = = ' to make logical judgments. The difference between the two is ' = = ' To make the logic, and so on, will be the type of conversion before the comparison. ' = = = ' is not. Thus, the result of the ' = = ' judgment may produce deviations. The difference between '!= ' and '!== ' is also true. This article advocates to use ' = = = ' To make the judgment of logic and so on, using '!== ' to make the judgment of logic unequal.

listing 6. Use of = = =

Code:
 code as follows:

<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 value of Valuea and Valueb two variables is clearly not equal, at least Valuea is a string, and Valueb is a number. But using ' = = ' to judge is, the program is output equal words. This is because the compiler, when comparing two variables, automatically converts VALUEB to strings, and then compares them to Valuea because of their different types. The result of the judgment obtained with ' = = = ' is consistent with the expected result.

+

The plus sign ' + ' is also one of the operators familiar with the programmer. JavaScript differs from other programming languages in that, in JavaScript, ' + ' can be used as a unary operator in addition to adding numeric values and strings, and converting strings to numbers. Therefore, if used improperly, it may be confused with the self-added character ' + + ' and cause a calculation error. This, as can be clearly seen in Listing 7.

Listing 7. Skillfully use + number

Code:
 code as follows:

<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

In this paper, we discuss the JavaScript code layout, naming, declaration, statement, and some special characters of the use of the Java programming specifications. In addition, there are many areas where you need to learn more about research, such as with, eval statements, and the use of this object, and so on. We are aware of its universality, but also need to pay attention to its specificity, in writing code to pay more attention to create more high-quality 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.