📜 ⬆️ ⬇️

13 interesting points from the javascript style guide from google

For those who have not yet seen: Google has published a style guide for JavaScript, which sets out the best stylistic practices (according to the company) for writing neat, understandable code.


This is not a rigid set of rules for competent programming in JavaScript, but simply a set of restrictions in order to withstand a single attractive style in all the source files. For JavaScript, such a guide is of particular interest - it is a very flexible and undemanding language, which gives much room for choice.

The most popular style guides are those offered by Google and Airbnb. If you spend a lot of time working with JS, I recommend to get acquainted with both. Below I will list the thirteen rules from the Google manual that I found particularly interesting. It affects everything: the stumbling blocks that cause the most controversy (gaps against tabulation, the debatable question of how to use semicolons), and some less discussed points that surprised me. All of this will definitely affect my future code writing practices.

For each rule, I will give a brief statement of the requirement, a quotation from the manual, where it is formulated in more detail, as well as, if possible, examples of its application along with fragments, where it is violated, so that it can be compared.
')

Use spaces, not tabs.


With the exception of newline characters, ASCII space (0x20) is the only character that should appear in the source files to indicate indentation. This implies that ... tabulation is not used for formatting.

Later, the guide also specifies that two spaces should be set for the indent, not four.

// bad function foo() { ∙∙∙∙let name; } // bad function bar() { ∙let name; } // good function baz() { ∙∙let name; } 

Semicolons are required


Each operator must end with a semicolon. To rely on its automatic affixing is prohibited.

I have no idea what explains this resistance to this idea, but the debate about whether it is necessary to permanently affix a semicolon in the JS code has recently reached the level of war between supporters of spaces and tabs. Google takes a strong position here, arguing in favor of semicolons.

 // bad let luke = {} let leia = {} [luke, leia].forEach(jedi => jedi.father = 'vader') // good let luke = {}; let leia = {}; [luke, leia].forEach((jedi) => { jedi.father = 'vader'; }); 

Do not use ES6 modules (for now)


At the moment, you should not use ES6 modules (for example, for exporting and importing keywords), since their semantics has not yet acquired the final look. Note that this rule will be revised when the semantics will be finally brought to the standard.

 // Don't do this kind of thing yet: //------ lib.js ------ export function square(x) { return x * x; } export function diag(x, y) { return sqrt(square(x) + square(y)); } //------ main.js ------ import { square, diag } from 'lib'; 

Horizontal alignment is not recommended (although not prohibited)


This practice is permitted, but not endorsed by Google’s style guide. It is not even necessary to maintain horizontal alignment where it has already been applied.

Horizontal alignment is a practice in which an arbitrary number of additional spaces are added to the code so that certain values ​​are located directly below the corresponding values ​​on the top line.

 // bad { tiny: 42, longer: 435, }; // good { tiny: 42, longer: 435, }; 

Do not use var anymore


Declare all local variables with const or let. Make const the default option, unless the variable needs to be assigned a new value. The var keyword cannot be used.

In the code examples on StackOverflow and other sites, I still come across var. I do not know whether these people have arguments in favor of such a choice, or they simply cannot give up the old habit.

 // bad var example = 42; // good let example = 42; 

Preference is given to arrow functions.


Arrow functions provide a concise syntax and thus solve a number of difficulties. Give them preference over keywords for functions, especially when it comes to nested functions.

To be honest, I like the dial functions simply because they look better and more accurate. But, as it turns out, they also serve a rather important purpose.

 // bad [1, 2, 3].map(function (x) { const y = x + 1; return x * y; }); // good [1, 2, 3].map((x) => { const y = x + 1; return x * y; }); 

Use wildcard strings instead of concatenation.


Using patterns in which strings are separated by the `character is preferable to complex string concatenation, especially in cases where they contain several string literals. Patterns can include several lines.

 // bad function sayHi(name) { return 'How are you, ' + name + '?'; } // bad function sayHi(name) { return ['How are you, ', name, '?'].join(); } // bad function sayHi(name) { return `How are you, ${ name }?`; } // good function sayHi(name) { return `How are you, ${name}?`; } 

Do not use line continuation for long lines.


Do not use the continuation of the string (in other words, do not end the string as part of a string literal with a backslash symbol) neither in ordinary string literals, nor in template literals.

Interestingly, here Google disagrees with Airbnb (their specifications can be found here). If Google recommends using concatenation for long strings (as shown below), the Airbnb style guide prescribes, in general, to do nothing and just continue the string as long as necessary.

 // bad (sorry, this doesn't show up well on mobile) const longString = 'This is a very long string that \ far exceeds the 80 column limit. It unfortunately \ contains long stretches of spaces due to how the \ continued lines are indented.'; // good const longString = 'This is a very long string that ' + 'far exceeds the 80 column limit. It does not contain ' + 'long stretches of spaces since the concatenated ' + 'strings are cleaner.'; 

for ... of - the optimal type of for cycles


With the release of ES6, there are now three different types of for loops in the language. You can apply them all, but if possible, for-of loops should be given priority.

In my opinion, this is a very strange advice, but I decided to include it all the same - it is curious that Google singles out for itself the favorite type of cycle. In general, I have always been under the impression that for ... in loops are more suitable for objects, and for ... of loops are better for working with arrays. That is, we have a situation where the tool is selected for the task.

Not that Google’s specification goes against this thought, but it’s still interesting to know that they have a particular favorite, and this particular one.

Do not use eval ()


Never use eval () or the Function (... string) constructor (except for program loaders). These functions carry a potential threat and simply do not work in CSP environments.

MDN on the eval () page even has a special section called “Never use eval ()!”

 // bad let obj = { a: 20, b: 30 }; let propName = getPropName(); // returns "a" or "b" eval( 'var result = obj.' + propName ); // good let obj = { a: 20, b: 30 }; let propName = getPropName(); // returns "a" or "b" let result = obj[ propName ]; // obj[ "a" ] is the same as obj.a 

Constants must write CAPSLOCK and be separated by underscores.


The names of the constants are written in a special format: in capital letters and with underscores between separate words.

If you are absolutely sure that the variable should remain unchanged, you can emphasize this by writing its name in capital letters. So the reader of the code will immediately understand that the variable is inviolable, in whatever fragment it meets.

An important exception to this rule is constants within a function. In their case, camel case should be used.

 // bad const number = 5; // good const NUMBER = 5; 

One variable - one declaration


Each local variable has a separate declaration. Declarations of the form let a = 1, b = 2 are not allowed.

 // bad let a = 1, b = 2, c = 3; // good let a = 1; let b = 2; let c = 3; 

Use single quotes, not double quotes.


Standard string literals are separated by single quotes ('), double (") are not used for this purpose.

Tip: if the string already contains a single quote character, consider using a template with backquotes to avoid formatting problems.

 // bad let directive = "No identification of self or mission." // bad let saying = 'Say it ain\u0027t so.'; // good let directive = 'No identification of self or mission.'; // good let saying = `Say it ain't so`; 

And finally


As I said at the beginning, it is not worth considering all this unshakable commandments. In addition to Google, there are other IT giants, and these rules are more advisory in nature.

But even with this proviso, style recommendations from a company like Google, which has many talented employees who write excellent code, are of considerable interest. You can follow these rules if you want to write “source code that is compatible with Google products,” or you can just give up on them.

Personally, it seems to me that the specifications of Airbnb are in many ways more attractive than those of Google. But no matter what position you take with respect to these rules, it is important to remember one thing: when working on any code in style, consistency must be maintained.

Source: https://habr.com/ru/post/358698/


All Articles