JavaScript Prerequisites: Google releases the JS code specification (GO)

Source: Internet
Author: User

What do you need to know about the JS code specification that Google publishes?

Translation | Whiteyin

Translation | Https://github.com/WhiteYin/translation/issues/10

Google has published a JS code specification for people who are not familiar with code specifications. It lists the best practices you should do to write code that is simple and understandable.

The code specification is not a rule for writing the correct JavaScript code, but rather a choice to maintain consistent source code authoring patterns. This is especially true for the JavaScript language, because it is flexible and less restrictive, allowing developers to use many different coding styles.

Google and Airbnb each occupy half of the current most popular coding specifications. If you're going to spend a lot of time writing JS code, I highly recommend that you read through the coding specifications of these two companies.

The next thing I want to write is the 13 rules that I personally think are closely related to daily development in Google's code specification.

The issues they deal with are very controversial, including tab and space, whether to force the use of semicolons, and so on. And some of the rules that surprised me often ended up changing the way I used to write JS code.

For each rule, I will first give a summary of the specification and then refer to the specification in detail. I will also cite some appropriate counter-examples to demonstrate the importance of complying with these rules.

Use spaces instead of tab

In addition to the Terminator sequence for each line, ASCII horizontal whitespace (0x20) is the only space character that can appear anywhere in the source file. This also means that the tab character should not be used and is used to control indentation.

The specification then states that indentation should be implemented using 2, instead of 4 space bands.

    1. // bad

    2. function foo() {

    3. ????let name;

    4. }

    5. // bad

    6. function bar() {

    7. ?let name;

    8. }

    9. // good

    10. function baz() {

    11. ??let name;

    12. }

You cannot omit a semicolon

Each statement must end with a semicolon. Does not allow the ability to rely on JS to automatically add semicolons.

Although I do not understand why there are objections to this rule, the current use of semicolons has obviously been as controversial as the "Space vs Tab" issue. And Google for this means that the semicolon is necessary, is not omitted.

    1. // bad

    2. let luke = {}

    3. let leia = {}

    4. [luke, leia].forEach(jedi => jedi.father = ‘vader‘)

    5. // good

    6. let luke = {};

    7. let leia = {};

    8. [luke, leia].forEach((jedi) => {

    9.  jedi.father = ‘vader‘;

    10. });

Do not use ES6 module for the time being

Because the semantics of the ES6 module are not yet fully determined, do not use it for the time being, such as the Export and import keywords. Please ignore this rule once their relevant specifications have been set up.

    1. //temporarily do not write the following code:

    2. //--- ---lib.js------

    3. export function Square (x) {

    4.     return x * x;

    5. }

    6. export function Diag (x, y) {

    7.     return sqrt ( Square (x) + square (y))

    8. }

    9.  

    10. //------main.js------

    11. import {square, diag} from ' lib ' ;

The Translator notes: It is not realistic to observe this norm, after all, there is now a Babel. And when using react, the best practice is to use the ES6 module.

Code is not recommended for horizontal alignment

Google's code specification allows for horizontal alignment of the code, but not recommended. This behavior should be avoided in the future even if the previous code has been dealt with horizontally aligned.

Horizontal alignment of the code adds a number of extra spaces to the code, which makes the characters adjacent to the two lines appear to be on a vertical line.

    1. // bad

    2. {

    3.  tiny:   42,  

    4.  longer: 435,

    5. };

    6. // good

    7. {

    8.  tiny: 42,

    9.  longer: 435,

    10. };

Eliminate Var

Declare all local variables using const or let. If a variable does not need to be re-assigned, a const should be used by default. You should refuse to use the keyword var.

I don't know because no one can persuade them, or because the stereotypes are hard to change. I can still see many people using VAR to declare variables in StackOverflow or elsewhere.

    1. // bad

    2. var example = 42;

    3. // good

    4. const example = 42;

Priority use of Arrow functions

The arrow function provides a concise syntax and avoids some questions about this point. Compared with the function keyword, developers should prefer to use the arrow functions to declare functions, especially to declare nested functions.

Frankly speaking, I thought that the function of the arrow is only simple and beautiful. But now I find that they still have a more important role to play.

    1. //Bad

    2. [ 1 , 2 , 3 ].map ( function (x) {

    3.   const y = x + 1 ;

    4.   return x * y;

    5. });

    6.  

    7. //Good

    8. [ 1 , 2 , 3 ].map ((x) + = {

    9.   const y = x + 1 ;

    10.   return x * y;

    11. });

Replacing a connection string with a template string

When working with multiline strings, the template string behaves better than a complex stitching string.

  1. // bad

  2. function sayHi(name) {

  3.  return ‘How are you, ‘ + name + ‘?‘;

  4. }

  5. // bad

  6. function sayHi(name) {

  7.  return [‘How are you, ‘, name, ‘?‘].join();

  8. }

  9. // bad

  10. function sayHi(name) {

  11.  return `How are you, ${ name }?`;

  12. }

  13. // good

  14. function sayHi(name) {

  15.  return `How are you, ${name}?`;

  16. }

Do not split long strings with line continuation characters

In JS, \ also represents the continuation of the line character. Google's code specification does not allow the use of line-continuation characters in either template strings or ordinary strings. Although this is allowed in ES5, \ This behavior causes some errors if you follow some end-whitespace characters, and these errors are difficult to notice when reviewing your code.

This rule is interesting because there is a different rule in the Airbnb code.

Google recommends the following, while Airbnb believes that it should be as natural as it should be, and how long it will take without special treatment.

  1. // bad (建议在PC端阅读)

  2. const longString = ‘This is a very long string that \

  3.    far exceeds the 80 column limit. It unfortunately \

  4.    contains long stretches of spaces due to how the \

  5.    continued lines are indented.‘;

  6. // good

  7. const longString = ‘This is a very long string that ‘ +

  8.    ‘far exceeds the 80 column limit. It does not contain ‘ +

  9.    ‘long stretches of spaces since the concatenated ‘ +

  10.    ‘strings are cleaner.‘;

Priority use for...of

In ES6, there are 3 different for loops. Although each has its own application scenario, Google still recommends using it for...of .

It's funny how Google specifically specifies a for loop. Although this is strange, it does not affect my acceptance of this view.

I used to think that it for...in was appropriate to traverse an object and for...of iterate over an array. Because I like this way of doing my own work.

Although Google's specifications conflict with this usage, Google's for...of preference still makes me feel very interesting.

Do not use the Eval statement

The eval or function (. String) structure is not used unless it is in code loader. This feature is potentially dangerous and does not work in a CSP environment.

There is a section in MDN that specifically mentions that you should not use the Eval statement.

    1. // bad

    2. let obj = { a: 20, b: 30 };

    3. let propName = getPropName();  // returns "a" or "b"

    4. eval( ‘var result = obj.‘ + propName );

    5. // good

    6. let obj = { a: 20, b: 30 };

    7. let propName = getPropName();  // returns "a" or "b"

    8. let result = obj[ propName ];  //  obj[ "a" ] is the same as obj.a

Naming conventions for constants

Constant naming should be in full-capitalization format and split with underscores

If you are certain and sure that a variable value will not be modified later, you can overwrite its name with the full capitalization mode, implying that it is a constant, and do not modify its value.

One thing to keep in mind when adhering to this rule is that if the constant is a function, you should use camel-like nomenclature.

    1. // bad

    2. const number = 5;

    3. // good

    4. const NUMBER = 5;

Declare only one variable at a time

Each variable declaration should correspond to only one variable. A statement like this should not appear leta=1,b=2; .

    1. // bad

    2. let a = 1, b = 2, c = 3;

    3. // good

    4. let a = 1;

    5. let b = 2;

    6. let c = 3;

Use single quotation marks

Only single quotes are allowed to wrap ordinary strings, and double quotes are forbidden. If the string contains single quote characters, the template string should be used.

    1. // bad

    2. let directive = "No identification of self or mission."

    3. // bad

    4. let saying = ‘Say it ain\u0027t so.‘;

    5. // good

    6. let directive = ‘No identification of self or mission.‘;

    7. // good

    8. let saying = `Say it ain‘t so`;

Summarize

As I said at the beginning, there are no commands in the specification that require enforcement. Although Google is one of the technology giants, the code specification is only used as a reference.

Google is a technology company with a talent pool that employs great programmers to write good code. It's interesting to be able to see the code specifications published by such a company.

If you want to implement a Google-style code, you can develop these specifications in your project. But you may not be in favor of the code specification, and no one will stop you from abandoning some of these rules.

I personally think that in some scenarios, Airbnb's code specification is better than Google's code specification. But no matter what kind of code you support, and no matter what type of coding you write, the most important thing is to keep the same code specification in mind all the time.

JavaScript Prerequisites: Google releases the JS code specification (GO)

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.