ads
Detail about google javascript's style.
ads
For those unfamiliar, Google publishes a style guide for writing JavaScript. It outlines best style practices (which Google believes) for writing clean and understandable code.
These are not hard and fast rules for writing valid JavaScript. It is not a convention for maintaining consistent and comfortable style choices in source files. This is of particular interest to JavaScript, a flexible and forgiving language that allows for many different style choices.
Google and Airbnb have two of the most popular style guides. I highly recommend checking both if you spend a lot of time writing JS.
Below are 13 rules that I consider to be the most interesting and relevant rules from Google's JS Style Guide.
Covers everything from hotly debated topics (tabs and spaces, and the controversial issue of how to use semicolons) to some obscure specs that surprised me. It will definitely change the way we write JS in the future.
For each rule, outline the specification, followed by supplementary quotes from the style guide that explain the rule in detail. Where appropriate, examples of style in action are provided and contrasted with code that does not follow the rules.
Use spaces instead of tabs
Except for end-of-line sequences, the only space character that appears anywhere in a source file is the horizontal ASCII space (0x20). This means... tab characters are not used for indentation.
The description below states that you should use 2 spaces (instead of 4) for indentation.
// bad
function foo() {
∙∙∙∙let name;
}
// bad
function bar() {
∙let name;
}
// good
function baz() {
∙let name;
}
semicolon expected
Each statement must end with a semicolon. Relying on automatic insertion of semicolons is prohibited
I can't imagine why anyone would disagree with this idea, but the consistent use of semicolons in JS has led to a new "space vs. tab" debate. Google is a firm defender of semicolons here.
// Bad
let luke = {}
let leia = {}
[luke, leia].forEach(jedi => jedi.father = 'vader')
// Good
let luke = {};
Leia = {};
[Luke, Leia].forEach((Jedi) => {
jedi.father = 'vader';
});
Don't use ES6 modules (yet)
ES6 modules (export and import keyword) should not be used yet. These semantics are not yet finalized. Please note that this policy will be revised once the semantics are fully standard compliant.
// Don't do this 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';
Landscape is discouraged (but not prohibited). You don't even have to maintain horizontal orientation where it's already been used.
Horizontal alignment is a method of adding a variable number of extra spaces to code so that certain tokens appear immediately below certain other tokens on the previous line.
// bad
{
small: 42,
long: 435,
};
// good
{
small: 42,
long: 435,
};
stop using var
make all local variables const Or declare it with let . Use const by default unless you need to reassign variables. Keyword var is not allowed.
I still see people using var in code examples on StackOverflow and elsewhere. I don't know if anyone is arguing about this or if it's just an old habit dying.
// bad
var example = 42;
// good
let example = 42;
arrow functions are preferred
arrow functions provide a concise syntax and solve many problems. Prefer arrow functions over the function keyword, especially in nested functions. It turns out that 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 template strings instead of concatenation
especially involving multiple string literals If so, use template strings (separated by `) via complex string concatenation. A template string can span multiple 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 continuations for long strings.
Do not use line continuation (that is, end a line in a string literal with a backslash) in either regular string literals or template string literals. ES5 allows this, but a slash followed by whitespace that isn't very noticeable to the reader can lead to tricky mistakes.
Interestingly, this is a rule that Google and Airbnb disagree on (see Airbnb's specs here).
Google recommends concatenating long strings (as shown below), but Airbnb's style guide recommends basically doing nothing and letting the long string do as much as you want. doing.
// bad (sorry, this doesn't display well on mobile)
const longString = 'This is a very long string. \
is way over the 80 column limit. Unfortunately, it contains a long space of \
. This is because the continuing line is indented \
.ads
// good
const longString = 'This is a very long string. ' +
'The limit of 80 columns is far exceeded. The concatenated ' +
' string is clean, so it does not contain the ' +
' long space.
``for... of'' is the preferred type of ``for loop''.
ES6 now includes three different types of for loops in the language. You can use all of them, but I recommend using for-of loops whenever possible.
This is weird if you ask me, but it's very interesting that Google declares the preferred for loop type, so I thought I'd include it.
for... in loops are good for objects, but for...
of was better suited for arrays. A "right tool for the right job" type of situation.
Google's spec here doesn't necessarily contradict this idea, but it's interesting to know that they particularly like this loop.
Don't use eval().
Do not use eval or Function(...string) constructors (except code loaders). These features are potentially dangerous and will not work in a CSP environment.
The MDN page for eval() even has a section "Don't 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. The
constants must be named with ALL_UPPERCASE separated by underscores.
If you are absolutely certain that a variable should never be changed, you can indicate this by capitalizing the name of the constant. This reveals the immutability of constants as they are used throughout the code.
A notable exception to this rule is when the constant is function related. In this case, it should be written in camelCase.
// bad
constant = 5;
// good
const NUMBER = 5;
one variable per declaration
Each local variable declaration declares only one variable. Not used.
// bad
let a = 1, b = 2, c = 3;
// good
let a = 1;
let b = 2;
let c = 3; Use single quotes.
Regular string literals are delimited by single quotes (') instead of double quotes (") and quote escapes. No self or mission identification.';
// good
let
Final Note
As I said at the beginning, these are not obligations, Google is just one of many tech giants and they are only recommendations.
Still, it's interesting to see the style recommendations issued by companies like Google. Google employs a lot of great people and spends a lot of time writing great code.
If you want to follow the "Google Compatible Source Code" guidelines, you can follow these conventions, but of course many people disagree.
Personally, I find Airbnb's specs to be more attractive than Google's in many cases. Regardless of your stance on these particular rules, it's important to maintain stylistic consistency when writing any kind of code.
Thanks for reading! If you've just transitioned his career into web/software development, I've written more on the subject here:
This is weird if you ask me, but it's very interesting that Google declares the preferred for loop type, so I thought I'd include it.
for... in loops are good for objects, but for...
of was better suited for arrays. A "right tool for the right job" type of situation.
Google's spec here doesn't necessarily contradict this idea, but it's interesting to know that they particularly like this loop.
Don't use eval().
Do not use eval or Function(...string) constructors (except code loaders). These features are potentially dangerous and will not work in a CSP environment.
The MDN page for eval() even has a section "Don't 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. The
constants must be named with ALL_UPPERCASE separated by underscores.
If you are absolutely certain that a variable should never be changed, you can indicate this by capitalizing the name of the constant. This reveals the immutability of constants as they are used throughout the code.
A notable exception to this rule is when the constant is function related. In this case, it should be written in camelCase.
// bad
constant = 5;
// good
const NUMBER = 5;
one variable per declaration
Each local variable declaration declares only one variable. Not used.
// bad
let a = 1, b = 2, c = 3;
// good
let a = 1;
let b = 2;
let c = 3; Use single quotes.
Regular string literals are delimited by single quotes (') instead of double quotes (") and quote escapes. No self or mission identification.';
// good
let
Final Note
As I said at the beginning, these are not obligations, Google is just one of many tech giants and they are only recommendations.
Still, it's interesting to see the style recommendations issued by companies like Google. Google employs a lot of great people and spends a lot of time writing great code.
If you want to follow the "Google Compatible Source Code" guidelines, you can follow these conventions, but of course many people disagree.
Personally, I find Airbnb's specs to be more attractive than Google's in many cases. Regardless of your stance on these particular rules, it's important to maintain stylistic consistency when writing any kind of code.
Thanks for reading! If you've just transitioned his career into web/software development, I've written more on the subject here:

0 Comments