JavaScript Style Guide: Key takeaways from Google’s Style Guide

Google JavaScript Style Guide

For those who may not know, Google publishes a JavaScript style guide of best practices for writing JavaScript code. It lays out (at least what Google believes to be) the best practices for writing clean, understandable JavaScript code. JavaScript does not have any fixed set of rules for writing valid code, only recommendations for maintaining consistent and appealing style choices throughout your code. JavaScript is a particularly flexible and forgiving language in this aspect. It allows the coding styles with a wide variety of stylistic choices at developers’ disposal.

The JavaScript style guides published by Google and Airbnb are two of the most popular ones available. I’d definitely recommend you check out both of them if you spend a lot of time writing JavaScript or even Typescript code.

In this article, we are going to see some of the noteworthy points from Google’s JavaScript Style Guide. They range from some of the hotly contested developer preferences (tabs versus spaces, and the controversial issue of how semicolons should be used), to a few more obscure specifications which surprised me. I personally do not follow any single JavaScript style guide. I try to take the best from each of them and customize as per my liking.

Here are some of the key takeaways from the Google’s JavaScript Style Guide to think about:

  1. Use const or let instead of var
  2. All Statements must end with a semicolon
  3. Horizontal alignment should be avoided
  4. Indent with spaces, not tabs
  5. Prefer Arrow functions over function keyword
  6. Use template literals instead of concatenation
  7. Don’t use eval()
  8. One variable per declaration
  9. Use single quotes instead of double quotes
  10. Constants should be named in CONSTANT_CASE
  11. Don’t use line continuations for long strings
  12. Prefer “for… of” for iterating

1. Use const or let instead of var

Use either const or let to declare all your variables. When declaring/initializing a new variable, always start with const by default, and if you know that the variable would need re-assignment, change it to let. The var keyword must not be used anymore.

I still see many developers using var around me, in the office as well as online. It could be for many reasons, like maintaining legacy code to old habits but we do need to start somewhere.

// bad
var name = 'Manish';

// good
const name = 'Manish';

// good
let name = 'Manish';
...
name = 'Rahul';

2. All Statements must end with a semicolon

A semicolon must be used at the end of every statement. Relying on automatic semicolon insertion is should be avoided. Personally, I just prefer to use a semicolon to end a statement. I can’t imagine why anyone is opposed to this idea. Trying to save some precious bytes? Anyway, good to see Google’s coming out defending the use of semicolons.

// bad
let firstName = 'John'
let lastName = 'Doe'

// good
let firstName = 'John';
let lastName = 'Doe';

3. Horizontal alignment should be avoided

This practice is permitted, but it is generally discouraged by the Google JavaScript Style guide. It is not even mandatory to maintain horizontal alignment in places where it was already used. Horizontal alignment is the practice of adding a variable number of additional spaces in your code, to make certain tokens appear directly below certain other tokens on previous lines. This is generally done for aesthetic purposes and does not have any technical advantages or disadvantages (As long as you minify your code before using it in live environments).

// bad
{
  small:               42,  
  aReallyLongProperty: 435, 
};

// good
{
  small: 42, 
  aReallyLongProperty: 435,
};

4. Indent with spaces, not tabs

The guide encourages the use of spaces instead of tabs for indentation. Each time a new block or block-like construct is opened, the indent increases by two spaces. When the block ends, the indent returns to the previous indent level. The indent level applies to both code and comments throughout the block

The guide further specifies you should use two spaces (not four) for indentation.

// 4 spaces - bad
if(x === y) {
∙∙∙∙doSomething();
}

// 1 space - bad
if(x === y) {
∙doSomething();
}

// 2 spaces - good
if(x === y) {
∙∙doSomething();
}

5. Prefer Arrow functions over function keyword

Arrow functions provide a concise syntax and fix a number of difficulties with this. Prefer arrow functions over the function keyword, particularly for nested functions. Arrow functions are particularly useful for calling into callbacks as they permit explicitly specifying which parameters to pass to the callback whereas binding will blindly pass along all parameters.

// 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;
});

6. Use template literals instead of concatenation

Use template strings (delimited with `) over complex string concatenation, particularly if multiple string literals are involved. Template strings may span multiple lines. Template literal spanning multiple lines does not need to follow the indentation of the enclosing block.

// bad
function getWelcomeText(name) {
  return 'Hi, ' + name + '. How are you?;
}

// good
function getWelcomeText(name) {
  return `Hi, ${name}. How are you?`;
}

7. Don’t use eval()

eval() allows you to parse and execute string as JavaScript code. The Google JavaScript style guide warns against using eval() or the Function(...string) constructor (except for code loaders). These features are potentially dangerous and simply do not work in CSP environments.

The MDN page for eval() even has a section called “Don’t use eval!”

Warning: Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use eval().

// BAD!
console.log(eval('2 + 2'));
// expected output: 4

// BAD!
console.log(eval(new String('2 + 2')));
// expected output: 2 + 2

// BAD!
console.log(eval('2 + 2') === eval('4'));
// expected output: true

8. One variable per declaration

Separate declarations should be used for each variable if you want to declare more than one variable. Every local variable declaration declares only one variable: declarations such as let a = 1, b = 2; should not be used.

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

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

9. Use single quotes instead of double quotes

Ordinary string literals are delimited with single quotes ('), rather than double quotes (").

Tip: If a string contains a single quote character, consider using a template string to avoid having to escape the quote.

// bad
let directive = "No identification of self or mission."

// good
let directive = 'No identification of self or mission.';

// good
let saying = `Say it ain't so`;

10. Constants should be named in CONSTANT_CASE

Constant names should use all uppercase letters, with words separated by underscores.
eg. GLOBAL_PATH;

If you’re absolutely sure that a variable shouldn’t change, you can indicate this by capitalizing the name of the constant. This makes the constant’s immutability obvious as it gets used throughout your code. A notable exception to this rule is if the constant is function-scoped. In this case, it should be written in camelCase.

// bad
const global_path= '/usr/test/bla/bla';

// bad
const globalPath= '/usr/test/bla/bla';

// good
const GLOBAL_PATH= '/usr/test/bla/bla';

11. Don’t use line continuations for long strings

Do not use line continuations (that is, ending a line inside a string literal with a backslash) in either ordinary or template string literals. Even though ES5 allows this, it can lead to tricky errors if any trailing whitespace comes after the slash, and is less obvious to readers.

Interestingly enough, Airbnb’s spec discourages using a backslash as well as concatenations. Airbnb advises against breaking the strings. While Google recommends concatenating longer strings (as shown below) Airbnb’s JavaScript style guide recommends essentially doing nothing and allowing long strings to go on as long as they need to.

I am not sure I agree with Airbnb’s recommendation here since I, as a developer, want most of the source content to be visible and avoid horizontal scrolling as much as possible.

// bad
const str = '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 str = '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.';

12. Prefer “for… of” for iterating

With ES6, the language now has three different kinds of for loops. The traditional for loop, for...in loop and for...of loop. All may be used, though forof loops should be preferred when possible.

Whenever using for...in, Object.prototype.hasOwnProperty should be used to exclude unwanted prototype properties.

Final Thoughts

Of course, none of these are necessary and your code does not automatically become bad if you’re not following the Google style guide, Airbnb style guide, or any other JavaScript style guide for that matter. Google is just one of many tech giants, and these are just recommendations. That being said, it is interesting to look at these style recommendations and decide for yourself how many of these you agree with.

You can follow these rules if you want to follow the guidelines for ‘Google compliant source code’ — but, of course, plenty of people disagree, and you’re free to go your own way.

Thanks for reading! hope this helps you in some way. Feel free to share this with your fellow JavaScript developers, Colleagues, and friends if you think this may help them or simply to open a new discussion.

You may also like: ES6/ECMAScript 2015 Features you should be using right now

Be sure to follow us on the social media to get notified about the latest posts as soon as they’re published

Leave a comment

Your email address will not be published. Required fields are marked *

2 thoughts on “JavaScript Style Guide: Key takeaways from Google’s Style Guide”