Exploring JavaScript: Basic coding specifications

Source: Internet
Author: User
Tags define function
It is important to establish and follow the encoding specifications, which keeps your code consistent, predictable, and easier to read and understand.

It is important to establish and follow the encoding specifications, which keeps your code consistent, predictable, and easier to read and understand. A new developer can join this team to read the specifications, understand the code written by other team members, and get started faster.

A lot of heated debate occurs at meetings or on the mail list, and the problem often targets specific aspects of some code specifications (such as code indentation, Tab key or space key ). If you are proposing to adopt norms in your organization, you are ready to face all kinds of objections or may sound different but strong points of view. Remember that building and unswervingly following a specification is more important than focusing on the details of the Specification.

Indentation)

The Code cannot be read without indentation. The only bad thing is inconsistent indentation, because it seems to follow the rules, but may be accompanied by chaos and surprises along the way. It is important to use indentation in a standardized manner.

Some developers prefer to use tab Tab indentation, because anyone can adjust their editor to display the tab with spaces they like. Some people like spaces-usually four. This doesn't matter, as long as everyone in the team follows the same rule. This book, for example, uses four spaces for indentation, which is also the default indentation in JSLint.

What should be indented? The rule is simple-something in curly brackets. This means that the function body, loop (do, while, for, for-in), if, switch, and object attributes in the object literal volume. The following code is an example of indentation:

function outer(a, b) {var c = 1,        d = 2,        inner;    if (a > b) {        inner = function () {            return {                r: c - d            };        };    } else {        inner = function () {            return {                r: c + d            };        };    }    return inner;}
Curly Braces {} (Curly Braces)

Curly braces (also known as braces, the same below) should always be used, even if they are optional. Technically, if there is only one statement in or for, curly braces are not required, but you should always use them, which makes the code more persistent and easy to update.

Imagine you have a for loop with only one statement. You can ignore curly braces without parsing errors.

// Bad instance for (var I = 0; I <10; I + = 1) alert (I );

However, if the following code is added to the subject loop:

// Bad instance for (var I = 0; I <10; I + = 1) alert (I); alert (I + "is" + (I % 2? "Odd": "even "));

The second alert is already out of the loop, and indentation may fool you. For the sake of long-term planning, it is best to always use curly braces, real-time value of a line of code:

// Good instance for (var I = 0; I <10; I + = 1) {alert (I );}

If conditions are similar:

// Bad if (true) alert (1); else alert (2); // good if (true) {alert (1) ;}else {alert (2 );}
Opening Brace Location)

Developers have different preferences for the left braces-the same row or the next row.

If (true) {alert ("It's TRUE! ");} // Or if (true) {alert (" It's TRUE! ");}

In this example, the benevolent and wise see wisdom, but there are also cases where different brackets may have different behavior characteristics. This is because the semi-colon insertion mechanism (semicolon insertion mechanic)-JavaScript is not picky. When you choose not to use the semi-colon to end a line of code, JavaScript will help you add it. This behavior may cause trouble. For example, when you return the object literal while the left parenthesis is in the next line:

// Warning: unexpected return value function func () {return // the following code is not executed {name: "Batman "}}

If you want the function to return an object containing the name attribute, you will be surprised. The function returns undefined due to the implicit semicolon. The preceding code is equivalent:

// Warning: unexpected return value function func () {return undefined; // the following code is not executed {name: "Batman "}}

In short, curly braces are always used and always placed in the same line as the previous statement:

function func() {   return {      name : "Batman"   };}

Note about semicolons: Like using curly braces, you should always use semicolons, even if they can be implicitly created by the JavaScript parser. This not only promotes more scientific and rigorous code, but also helps solve problems, as shown in the previous example.

Space (White Space)

The use of spaces also helps improve code readability and consistency. When writing an English sentence, the interval is used after the comma and period. In JavaScript, you can add an interval after the list expression (equivalent to a comma) and the concluding sentence (relative to the completed "idea") according to the same logic.

Spaces are applicable:

  • Parts separated by semicolons in a for loop: for example, for (var I = 0; I <10; I + = 1 ){...}
  • Multi-variables (I and max) initialized in the for Loop: for (var I = 0, max = 10; I <max; I + = 1 ){...}
  • Separate the commas (,) of the array items: var a = [1, 2, 3];
  • Var o = {a: 1, B: 2 };
  • Define function parameters: myFunc (a, B, c)
  • Before the braces of the function declaration: function myFunc (){}
  • Behind the function of an anonymous function expression: var myFunc = function (){};

Using spaces to separate all operators and operation objects is another good use, which means that +,-, *, =, <, >,<=, >=, === ,! =, &, |, + =, And so on. spaces are required.

// Loose and consistent spacing // make the code easier to read // make it more "breathable" var d = 0, a = B + 1; if (a & B & c) {d = a % c; a + = d ;}// negative example // missing or spacing is different // make the code confused var d = 0, a = B + 1; if (a & B & c) {d = a % c; a + = d ;}

The last space to be noted is the bracket spacing. It is best to use spaces:

  • Before the left curly brackets of functions, if-else statements, loops, and object literal values ({)
  • Right curly braces (}) between else and while (})

The space is used to increase the file size, but the compression does not.

There is a often overlooked use of vertical spaces in terms of code readability. You can use empty lines to separate code units, just like using paragraphs in a literary file.

Naming Conventions)

Another way to make your code more predictable and maintainable is to adopt naming rules. This means that you need to name your variables and functions in the same form. The following are some recommended naming rules. You can use them as they are, or adjust them based on your preferences. Similarly, compliance is more important than compliance.

Capitalizing Constructors)

JavaScript does not have classes, but there are constructors called by new:

var adam = new Person();

Because the constructor is still a function, you can only look at the function name to tell you whether it should be a constructor or a normal function. When naming constructor, uppercase letters have an implication. Functions and methods that Use lowercase names should not be called using new:

function MyConstructor() {...}function myFunction() {...}
Separate Words)

When your variable or function name has multiple words, it is best to keep a unified rule for word separation. A common practice is called "Camel ", that is, lowercase words, and the first letter of each word.

For constructors, you can use the upper camel case method, such as MyConstructor (). For functions and method names, you can use the lower camel case method, such as myFunction (), calculateArea (), and getFirstName ().

What if the variable is not a function? Developers usually use a small camper name method, but there is another way to connect all words with lowercase strikethroughs: for example, first_name, favorite_bands, and old_company_name, this markup helps you intuitively distinguish functions and other identifiers-prototypes and objects.

ECMAScript uses the Camel flag Method for attributes and methods, although the multi-word attribute name is rare (the lastIndex and ignoreCase attributes of the regular expression object ).

Other Naming forms (Other Naming Patterns)

Sometimes, developers use naming conventions to supplement or replace language features. For example, JavaScript does not define constants (although some built-in methods such as Number, MAX_VALUE ), therefore, developers use the uppercase specification of all words to name variables that will not change in the life cycle of the program, such:

// Precious constant. Only the var PI = 3.14, MAX_WIDTH = 800, can be viewed far away;

Another practice is to write all global variables in uppercase. Naming global variables in uppercase can enhance the practice of reducing the number of global variables and make them easy to differentiate.

Another type of simulated function is a private member. Although it can be implemented in JavaScript, it is easier for developers to use only one underline prefix to indicate a private property or method. Consider the following example:

var person = {    getName: function () {        return this._getFirst() + ' ' + this._getLast();    },    _getFirst: function () {        // ...    },    _getLast: function () {        // ...    }};

In this example, getName () indicates a public method and some stable APIs. While _ getFirst () and _ getLast () indicate private. They are still common methods, but they are not guaranteed to work in the next version by warning the user of the person object using the underline prefix. They cannot be used directly. Note that JSLint has some non-bird underline prefixes, unless you have set the noman option to: false.

Below are some common _ private specifications:

  • Use the trailing underline to indicate private, such as name _ and getElements _()
  • Use the _ protected attribute of an underline prefix to indicate _ private? (Private) attributes
  • Some of the built-in variable attributes in Firefox do not belong to the technical part of the language. They are expressed by two prefix underscores and two backticks, for example, __proto _ and _ parent __.
Writing Comments)

You must comment out your code, even if no one else has the same contact with you. Generally, when you study a problem in depth, you will know exactly what the code is for. However, when you come back one week later, it may also take a lot of brain cells to figure out how to work.

Obviously, annotations cannot go extreme: each individual variable or a single row. However, you should generally record all functions, their parameters and return values, or any unusual techniques and methods. Think of annotations to give readers a lot of tips for the future of your code; readers need to (do not read too much) only comment and function attribute names to understand your code. For example, if you have five or six lines of programs that execute a specific task and you provide a line of code purpose and why it is described here, you can skip this section. There are no hard-coded comments. Some parts of the Code (such as regular expressions) may have more comments than the code.

The most important habit, however, is to keep comments updated in a timely manner, because outdated comments are more misleading than those without comments.

Additional reading

The topic list of this article is as follows:

  1. How should we understand the working principle of the JavaScript engine?
  2. JavaScript exploration: the importance of writing maintainable code
  3. JavaScript exploration: exercise caution when using global variables
  4. JavaScript exploration: var pre-parsing and side effects
  5. JavaScript exploration: for Loop (for Loops)
  6. JavaScript exploration: for-in loop (for-in Loops)
  7. Exploring JavaScript: Prototypes is too powerful
  8. JavaScript: eval () is the devil"
  9. JavaScript exploration: Using parseInt () for Numerical Conversion
  10. Exploring JavaScript: Basic coding specifications
  11. JavaScript exploration: function declaration and function expression
  12. JavaScript exploration: Name function expressions
  13. JavaScript: function name in the debugger
  14. JavaScript: JScript Bug
  15. JavaScript exploration: Memory Management of JScript
  16. Exploring JavaScript: SpiderMonkey's quirks
  17. JavaScript exploration: an alternative solution to naming function expressions
  18. JavaScript exploration: Object
  19. JavaScript exploration: Prototype chain
  20. JavaScript exploration: Constructor
  21. JavaScript probing: executable context Stack
  22. Execution context 1: Variable object and activity object
  23. Execution context 2: Scope chain Scope Chains
  24. Execution context 3: Closure Closures
  25. Execution context 4: This pointer
  26. Exploring JavaScript: Powerful prototype and prototype chain
  27. JavaScript Functions 1: function declaration
  28. JavaScript function 2: function expressions
  29. JavaScript function 3: function expressions in a group
  30. JavaScript function 4: function Constructor
  31. JavaScript variable object 1: VO Declaration
  32. JavaScript variable object 2: VO in different execution contexts
  33. JavaScript variable object 3: two stages of execution Context
  34. JavaScript variable object IV: Variables
  35. Property of the JavaScript variable object __parent _
  36. JavaScript scope chain 1: Scope chain Definition
  37. JavaScript scope chain 2: function Lifecycle
  38. JavaScript scope chain 3: Scope chain features
  39. JavaScript closure 1: Introduction to closures
  40. JavaScript closure 2: Implementation of closure
  41. JavaScript closure 3: Closure usage

This article is available at http://www.nowamagic.net/librarys/veda/detail/1629.

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.