JavaScript code readability

Source: Internet
Author: User
Tags readable uppercase letter

Most of the readability is related to the indentation of the code, and you must ensure that the code is well-formed. The other side of readability is the comment, in general, there are some places that need to be commented

1.1.1 Functions and methods

Each function or method should contain a comment describing its purpose and the algorithm used to complete the task, stating that the prior assumptions are also important, such as what the parameters represent, whether the function has a return value, etc.

1.1.2 Large Segment Code

Multiple lines of code to complete a single task should be preceded by a comment describing the task

1.1.3 Complex algorithms

If you use a unique way to solve a problem, explain how you do it in comments, not just to help other people who are browsing your code, but also to help you understand it the next time you check your code yourself.

1.1.4 Hack

Because there are browser differences, JavaScript code generally contains some hack, do not assume that other people can read the code to understand hack to cope with the browser problem, if because a browser can not use the normal method, so you need to use a few different methods, Then put this information in the comments.

1.1.5 Code layout 1.1.5.1 Line length

each line of code should be less than 80 characters. If your code is longer, you should try to choose a line break, and the next line of code should indent 4 spaces. This allows the code to be neatly formatted, reducing the fatigue of reading code to enhance the readability of the Code

1.1.5.2 End of Line

The JavaScript statement should end with a semicolon. But most browsers allow you to not write semicolons, as long as there is a newline character where the semicolon should be. But what are the considerations if the line of code is longer and needs to be wrapped? NewLine should be selected after the operator and punctuation, preferably after the comma ', ', and not in the variable name, string, number, or ' "" "+ +"--"and other symbols after the line . This can effectively prevent copying, pasting errors caused by, and can effectively enhance the readability of the code.

For example: var Valueb = Valuea///bad
+1;

Can be replaced by: var VALUEC = Valueb +///good
Valuea;

1.1.5.3 notes

We will emphasize the number of comments in the code, and despise the improvement of the quality of the annotations. Coding is to add comments in a timely manner, which will bring great convenience to the maintenance personnel of subsequent code. However, if the comments do not pay attention to the update, or due to copy, paste caused by the wrong comments, it will mislead the reader, but to the reading barrier, in addition to the comments to update in a timely manner , we should also pay special attention to the content of the comments. Note to be as simple as possible, clear, avoid the use of obscure language, while emphasizing the meaning of annotations , the less intuitive part of the annotation.

For example:

Following section was used to initialize Golbal variables (good)
var Valuea = 0; Initialize Valuea to being Sero (bad)
var valueb = 1;
...
Call F1 function after waiting for seconds. (good)
SetTimeout (f1,50000); Set timeout to BES 20s (copy error)

Function description of the large function block:

/*
* @desc: Function description
* @param: Parameter description
* @return: Return value
*/

1.1.5.4 Indent

It is recommended to use 4 spaces to indent

1.1.5.5 whitespace characters

Proper blank lines can greatly improve the readability of your code and make your code logic more readable. At the same time, in the expression of the appropriate left blank, will also give the code to read the convenience, the keyword after the parentheses, it is best to leave the keyword and the opening parenthesis ' (' left blank , such as for, if, while and so on. It is not advisable to leave whitespace between the function name and the parentheses , but if anonymous, you must leave blank between function and opening parenthesis ' ('), otherwise the editor will mistakenly assume that the function is called functions. In the expression, the two-tuple operator (except the opening parenthesis ' (', the left parenthesis ' [', the scope Point '). It is best to leave a blank between the two operands. The unary operator (not the word typeof, etc.) and its operands should not be left blank. The comma ', ' behind the need to leave blank to show clear parameter interval, variable interval and so on. Semicolon '; ' This usually indicates the end of the expression statement, and should be blank line. in the for in a conditional statement, the semicolon should be left blank .

The summary is that indents and annotations can lead to more readable code, and that the use of blank lines to separate logically related blocks of code can improve the readability of the program and increase the readability of the program just to make it easier to maintain the code in the future.

1.2 Variables and function naming

JavaScript is strictly case-sensitive, and the name follows the following rules:

    • The first character must be a letter, an underscore, or a dollar sign $
    • Other characters can be letters, underscores, dollar signs, or numbers
    • Names of variables, arguments, member variables, functions, and so on are all prefaced with lowercase letters, and the name of the constructor begins with an uppercase letter
    • Variables beginning with underscore ' _ ' are generally used to identify private/local members
    • Variables beginning with the dollar sign ' $ ' are used to identify system-related, such as system processes. You should avoid naming identifiers with the underscore ' _ ' or dollar sign ' $ '. Reduce the reading burden of your code as much as you can

Each line contains a maximum of one statement, you must place the semicolon at the end of a simple statement, although the semicolon in JavaScript is optional, but in order to compress after the error is not easy, mandatory must each JS code to the end of a semicolon

1.2.1 Variable name should be a noun

such as car or person, if it is a private variable, then the name is underlined

1.2.2 function name should start with a verb

For example, GetName (), a function that returns a Boolean type value is typically started with an IS, such as isenable (), if it is a normal function, the first letter is lowercase, and if it is a constructor, the first letter is capitalized. There should be no spaces between the function name and (left parenthesis). ) (the closing parenthesis) should be inserted between the {(opening curly brace) and the beginning of the program body with a space,} (the closing brace) should be in the same line as the function name and should not be another line

1.2.3 variables and functions should use a logical name

Do not worry about length, length problems can be handled and compressed by

1.2.4 all variable declarations need to be placed at the top of the function declaration, or at the beginning of the scope declaration 1.3 variable Type Transparency

Because JavaScript is a weak type (also called loosely typed) language, it is easy to forget the type of data that a variable should contain. Use the Hungarian notation to specify the variable type, and the Hungarian notation is to precede the variable name with one or more characters to represent the data type. The most traditional Hungarian notation in JavaScript is a single character representing the base type: the "O" code object, "S" for the string, "I" for the Integer, "F" for the floating-point number and "B" for the Boolean. As shown below

var bfound; Boolean type

var ICount; Integer

var sName; String

var Operson; Object

A little comment on the JavaScript variable declaration

The For loop in ECMAScript does not create a local context relative to C/A + +.

For (var k in {a:1, B:2}) {  alert (k);} alert (k);//Although the loop has ended but the variable k is still in the current scope

At any time, a variable can only be declared by using the var keyword.

The above assignment statement:

A = 10;

This simply creates a new property for the global object (but it is not a variable). "Not a variable" does not mean that it cannot be changed, but that it does not conform to the concept of a variable in the ECMAScript specification, so it is "not a variable" (it can be a property of a global object because there is a global object in JavaScript, Such an operation does not declare a variable but adds an a property to the global object.

Let's look at a simple example to illustrate the problem.

if (! (" A "in window) {    var a = 1;} alert (a); 

First, all global variables are properties of the window, and the statement var a = 1; equivalent to WINDOW.A = 1;

You can detect if a global variable is declared in the following way

"Variable name" in window

Second, all the variable declarations are at the top of the range scope and look at similar examples:

Alert ("A" in window); var A;

At this point, although the declaration is after alert, the alert pops up is still true, because the JavaScript engine first graves all the variable declarations and then moves the variable declarations to the top, and the final code effect is this:

var a;alert ("a" in window);

Third, you need to understand that the meaning of the topic is that the variable declaration is advanced, but the variable assignment is not, because this line of code includes the variable declaration and variable assignment.

You can split the statement into the following code:

var A;    Statement A = 1;    Initialize Assignment

So the summary is that when the variable declaration and assignment are used together, the JavaScript engine automatically divides it into two parts in order to advance the variable declaration, not to advance the assignment because he has the potential to influence the code to perform unexpected results.

The code in the title is equivalent to:

var a;if (! (" A "in window)) {    a = 1;} alert (a);  

According to the above example analysis, declare the variable if it is declared in front of the local variable must be added Var, if the declaration is the global variable can not add var (it is better to limit the number of global variables, try to use local variables)

Here are a few features that use Var

Declaring a variable multiple times with the Var statement is not only legal, but it does not cause any errors. If a repeating declaration has an initial value, it assumes the role of an assignment statement. If a duplicate declaration does not have an initial value, it does not have any effect on the existing variable.

Variables that do not have a VAR declaration are present as global variables, and variables declared with VAR are local variables, especially inside the function. And, after testing, the Var declaration is faster than without the Var. As much as possible in the function of local variables, so that is safe and fast, variable operation is more reasonable, not because the function of the random operation of global variables resulting in a logic error.

When declaring an object, it is best to use the object's self-polygon amount, which is much faster than the new method.

Variable names are taken by themselves, and in order to take care of semantics and specifications, variable names may be slightly longer, but note that the length of variable names can also affect the speed of code execution. Long variable name declarations do not perform as quickly as they are short.

JavaScript code readability

Related Article

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.