Table of Contents
Use spaces instead of tabs" >Use spaces instead of tabs
The semicolon cannot be omitted" >The semicolon cannot be omitted
Don’t use the ES6 module for the time being" >Don’t use the ES6 module for the time being
Horizontal alignment of code is not recommended" >Horizontal alignment of code is not recommended
Prevent var" >Prevent var
Use arrow functions first" >Use arrow functions first
Use templatesStringsReplace connection strings" >Use templatesStringsReplace connection strings
不要使用续行符分割长字符串" >不要使用续行符分割长字符串
优先使用for...of" >优先使用for...of
不要使用eval语句" >不要使用eval语句
常量的命名规范" >常量的命名规范
每次只声明一个变量" >每次只声明一个变量
使用单引号" >使用单引号
总结" >总结
Home Web Front-end JS Tutorial What code specifications for JS have been released by Google?

What code specifications for JS have been released by Google?

May 26, 2018 pm 04:37 PM
js Code specifications

This time I will bring you the code specifications released by Google about JS. The following is a practical case, let’s take a look.

Google has released a JS code specification for those who are not yet familiar with coding specifications. It lists best practices for writing concise and understandable code.

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

Google and Airbnb each occupy half of the most popular coding standards. If you will invest a long time in writing JS code, I strongly recommend that you read through the coding standards of these two companies.

What I want to write next are the thirteen rules that I personally think are closely related to daily development in Google's code specifications.

The issues they deal with are very controversial, including tabs and spaces, whether to force the use of semicolons, etc. There are also some rules that surprise me and often end up changing my habits of writing JS code.

For each rule, I will first give a summary of the specification and then quote the detailed description from the specification. I will also give some appropriate counterexamples to demonstrate the importance of following these rules.

Use spaces instead of tabs

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

The specification later states that indentation should be achieved using 2 spaces instead of 4.

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

The semicolon cannot be omitted

Each statement must end with a semicolon. Relying on JS's ability to automatically add semicolons is not allowed.

Although I don't understand why anyone would object to this rule, the use of semicolons has apparently become as controversial as the "spaces vs tabs" issue. Google said that the semicolon is necessary and cannot be omitted.

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

Don’t use the ES6 module for the time being

Since the semantics of the ES6 module are not yet completely determined, do not use it for the time being, such as export and import keys Character. Once their specifications are finalized, please ignore this rule.

// 暂时不要编写下面的代码:
//------ 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';
Copy after login

Translator's Note: I feel that it is not realistic to comply with this norm. After all, babel already exists. And when using React, the best practice is to use ES6 modules.

Google's code specifications allow but do not recommend horizontal alignment of code. Even if horizontal alignment was done in the previous code, this behavior should be avoided in the future.

Aligning the code horizontally will add some extra spaces in the code, which makes the characters on two adjacent lines appear to be on a vertical line.

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

Prevent var

Use const or let to declare all local variables. If the variable does not need to be reassigned, const should be used by default. Use of the keyword var should be rejected.

I don’t know if it’s because no one can convince them, or if it’s because old habits die hard. Currently I still see many people using var to declare variables on StackOverFlow or elsewhere.

// bad
var example = 42;
// good
const example = 42;
Copy after login

Use arrow functions first

Arrow functions provide a concise syntax and avoid some problems related to this pointing. Compared with the function keyword, developers should give priority to using arrow functions to declare functions, especially to declare nested functions.

To be honest, I once thought that the role of arrow functions was only to be simple and beautiful. But now I find that they have a more important role.

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

Use templatesStringsReplace connection strings

When dealing with multi-line strings, template strings It performs better than complex concatenated strings.

// 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}?`;
}
Copy after login

不要使用续行符分割长字符串

在JS中,\也代表着续行符。Google的代码规范不允许在不管是模板字符串还是普通字符串中使用续行符。尽管ES5中允许这么做,但如果在\后跟着某些结束空白符,这种行为会导致一些错误,而这些错误在审阅代码时很难注意到。

这条规则很有趣,因为Airbnb的规范中有一条与之不相同的规则

Google推荐下面这样的写法,而Airbnb则认为应该顺其自然,不做特殊处理,该多长就多长。

// bad (建议在PC端阅读)
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.';
Copy after login

优先使用for...of

在ES6中,有3种不同的for循环。尽管每一种有它的应用场景,但Google仍推荐使用for...of。

真有趣,Google居然会特别指定一种for循环。虽然这很奇怪,但不影响我接受这一观点。

以前我认为for...in适合遍历Object,而for...of适合遍历数组。因为我喜欢这种各司其职的使用方式。

尽管Google的规范与这种使用方式相冲突,但Google对for...of的偏爱依然让我觉得十分有趣。

不要使用eval语句

除非是在code loader中,否则不用使用eval或是Function(...string)结构。这个功能具有潜在的危险性,并且在CSP环境中无法起作用。

MDN中有一节专门提到不要使用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
Copy after login

常量的命名规范

常量命名应该使用全大写格式,并用下划线分割

如果你确定一定以及肯定一个变量值以后不会被修改,你可以将它的名称使用全大写模式改写,暗示这是一个常量,请不要修改它的值。

遵守这条规则时需要注意的一点是,如果这个常量是一个函数,那么应该使用驼峰式命名法。

// bad
const number = 5;
// good
const NUMBER = 5;
Copy after login

每次只声明一个变量

每一个变量声明都应该只对应着一个变量。不应该出现像let a = 1,b = 2;这样的语句。

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

使用单引号

只允许使用单引号包裹普通字符串,禁止使用双引号。如果字符串中包含单引号字符,应该使用模板字符串。

// 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`;
Copy after login

总结

就像我在开头所说那样,规范中没有需要强制执行的命令。尽管Google是科技巨头之一,但这份代码规范也仅仅是用来当作参考罢了。

Google是一家人才汇聚的科技公司,雇佣着出色的程序员来编写优秀的代码。能够看到这样的公司发布的代码规范是一件很有趣的事情。

如果你想要实现一种Google式的代码,那么你可以在项目中制定这些规范。但你可能并不赞成这份代码规范,这时也没有人会阻拦你舍弃其中某些规则。

我个人认为在某些场景下,Airbnb的代码规范比Google的代码规范要出色。但不管你支持哪一种,也不管你编写的是什么类型的代码,最重要的是在脑海中时刻遵守着同一份代码规范。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样利用JS实现动态进度条

如何使用js+css实现打字效果

The above is the detailed content of What code specifications for JS have been released by Google?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles