Highlights From The Javascript Style Guide of Google

Highlights from the JavaScript Style Guide of Google
by Janeth Kent Date: 27-02-2019 javascript JavaScript Style Guide Google

For anyone who is not already acquainted with it, Google provides a style guide for writing JavaScript that gives the best stylistic practices for writing clean, understandable code (what Google believes to be).

The guide does not present difficult rules for writing valid JavaScript, but only tips to keep the source files consistent and attractive.

This is extremely interesting for JavaScript, a flexible language that enables a wide range of stylistic choices.

Two of the most popular style guides are currently available from Google and Airbnb. If you spend a lot of time writing JS, we definitely recommend that you check it out.

The following is an analysis of the points of the Google JS Style Guide that we consider to be fundamental

They deal with everything from heavily contested issues (tabs versus spaces and the controversial question of how to use semicolons) to some more arcane specifications that impressed us.

We will provide a summary of the specification for each rule, followed by a supporting quote from the style guide that details the rule. We will also give an example of the style in practice where applicable and contrast it with code that does not follow the rules.

Use spaces, not tabs

The ASCII horizontal space character (0x20) is the only whitespace character to appear anywhere in a source file, apart from the line terminator sequence. This means that the characters on the tab are not used for indentation.

The guide indicates that two spaces (not four) should be used for indentation.

// bad
function foo() {
∙∙∙∙let name;

// bad
function bar() {
∙let name;

// good
function baz() {
∙∙let name;

Semicolons ARE required

Every statement must be terminated with a semicolon. Relying on automatic semicolon insertion is forbidden.

While we can't imagine why anyone opposes this idea, the consistent use of semicolons in JS is becoming a new debate about 'spaces versus tabs.' In defense of the semicolon, Google is coming out firmly here.

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

Don’t use ES6 modules (yet)

Do not use ES6 modules yet (i.e. the export and importkeywords), as their semantics are not yet finalized. Note that this policy will be revisited once the semantics are fully-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 discouraged (but not forbidden)

This practice is allowed, but Google Style generally discourages it. Horizontal alignment in places where it has already been used is not even required.

Horizontal alignment is the practice of adding a variable number of additional spaces in your code to make certain tokens appear on previous lines directly below certain other tokens.

// bad
  small:   42,  
  big: 435, 
// good
  small 42, 
  big: 435,

Don’t use var anymore

With either const or let, declare all local variables. Unless a variable needs to be reassigned, use const by default. The keyword of var should not be used.

We still see people on StackOverflow and elsewhere using var in code samples. If people argue for it, or if it's just a case of old habits dying hard, we can't say.

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

Arrow functions are preferred

Arrow functions provide a concise syntax and resolve a number of problems. Prefer arrow functions over the keyword function, especially for nested functions

We'll be honest, we just thought arrow functions were great because they were more concise and more pretty to look at. It also turns out that they serve a very useful function.

// 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

Use template strings (delimited with `) over complex string concatenation, particularly if multiple string literals are involved. Template strings may 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}?`;

Don’t use line continuations for long strings

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

Interestingly enough, Google and Airbnb disagree with this rule (the spec of Airbnb is here).

While Google suggests connecting longer strings (as appeared as follows) Airbnb's style control prescribes basically doing nothing, and enabling long strings to go on as long as they have to.

// 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” is the preferred type of ‘for loop’

With ES6, the language now has three different kinds of forloops. All may be used, though for-of loops should be preferred when possible.

If you ask us, this is a strange one, but we thought we'd include it because Google considers a preferred type of for loop.

We've always been under the impression that for... in loops were better for objects, while for... of were better suited to arrays. A ‘right tool for the right job’ type situation.

While Google's detail here doesn't really negate that thought, it is as yet intriguing to realize they have an inclination specifically for this loop.

Don’t use eval()

Do not use 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() has a section called “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

Constants should be named in ALL_UPPERCASE separated by underscores

Constant names use CONSTANT_CASE: all uppercase letters, with words separated by underscores.

In case you're certain beyond a shadow of a doubt that a variable shouldn't change, you can demonstrate this by capitalizing the name of the constant. This makes the constant’s immutability obvious as it gets used throughout your code.

If the constant is function - scoped, it provoques a notable exception to this rule. It must be written in camelCase in this case.

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

One variable per declaration

Every local variable declaration declares only one variable: declarations such as let
// bad
let a = 1, b = 2, c = 3;
// good
let a = 1;
let b = 2;
let c = 3;

Use single quotes, not 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."
// 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`;


These are not directives, as we said at the beginning.

Google is one of the many technology giants, and these are only guidelines. All of that said, of it's fascinating to look at a company like Google's which employ a lot of brilliant developers who spend a lot of time writing great code, giving style recommendations.

If you want you can follow the "Google Compliant Source Code" guidelines", but, of course, several people disagree, and you can brush off any or all of this.

We definitely think there are several cases where the specifications of Airbnb are more attractive than those of Google. Regardless of the position you take on these specific rules, it is still important to bear in mind the stylistic consistency when writing any code.




Original Source

Business vector created by freepik - www.freepik.com

by Janeth Kent Date: 27-02-2019 javascript JavaScript Style Guide Google hits : 6174  
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN END DEVELOPMENT.


Related Posts

Validating HTML forms using BULMA and vanilla JavaScript

Today we are going to write about contact forms and how to validate them using JavaScript. The contact form seems to be one of the top features of every basic home…

A FULFILLED PROMISE - Using the FETCH API to make AJAX calls

In this article we talked about what AJAX calls are and how to use them in a traditional way, by using the XMLHttpRequest (XHR) object. In short, thanks to AJAX…

How to use Parallax.js effect on your website

Today, we're going to write about the parallax effect, similar to parallax scrolling, and how to implement it to improve your landing page. In webdev, they say mobile first -…

How to make the website's dark mode persistent with Local Storage, CSS and JS

Recently we wrote about how to do a switchable alternative color mode or theme, a very useful and popular feature to websites. Today’s article is going to be about how…

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

Javascript: what are callbacks and how to use them.

Today we are going to learn about a concept that is widely used in javascript and that is used quite a lot by today's frameworks, libraries, especially NodeJS. This is…

HTTP Cookies: how they work and how to use them

Today we are going to write about the way to store data in a browser, why websites use cookies and how they work in detail. Continue reading to find out how…

The package managers npm and yarn: main differences

Npm and yarn are package managers that help to manage a project’s dependencies. A dependency is, as it sounds, something that a project depends on, a piece of code that…

The Javascript asign() method to merge and clone objects

In this article, we will be covering Object.assign()method in javascript in detail with examples. A javascript object is a collection of key-value pairs. Keys are also known as properties of object. Keys…

All the javascript functions and methods to manipulate arrays

This article will show that the prominent JavaScript array functions are .map(), .filter(), and .reduce(), and will then go through examples of instances in which .every() and .some() would save…

TypeScript: The evolution of JavaScript

When you're involved in the development of a large project, programming languages like JavaScript don't seem to be the best solution. Their lack of elements such as Language Aids has…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration