By Yin Ronghui @Tencent

Directory:

1. Variable correlation

2. Functional correlation

Use ES6 as much as possible, and new ES7 syntax if possible

Writing code is much better than it used to be. Eslint,prettier, Babel (writing new syntax), etc. However, no technology can solve the problem of readability (whether code can be read by future self and colleagues) because only people can solve it themselves. We’re going to write the code on the left side of the diagram and we’re basically done.

Note: Due to my personal level and perspective, this article does not completely cover common bad coding habits, so if you need to add anything, please feel free to comment at the bottom of this article, or directly to my Github post. For useful, will be added to my nuggets and Github. At the same time, if you think your article is ok, Please send your precious Star in my Github. Your Star is the biggest motivation for me to continue to write my article.

1. Variable correlation

(1) Definition of the number of variables

NO: abusing variables:

let kpi = 4; Function example() {var a = 1; var b = 2; var c = a+b; var d = c+1; var e = d+a; return e; }Copy the code

YES: Data needs to be used only once or not to be loaded into variables

let kpi = 4; Function example() {var a = 1; function example() {var a = 1; var b = 2; return 2*a+b+1; }Copy the code

(2) Variable naming

NO: Short for feeling good about yourself

let fName = 'jackie'; // It looks like the naming is standard, abbreviations, humps are used, all kinds of tools to check the specification pass ESlint, But, fName is what? What are you doing? let lName = 'willen'; // This is the same problem as aboveCopy the code

YES: You don’t need to comment every variable, just read the name

let firstName = 'jackie'; // How about that? Let lastName = 'willen';Copy the code

(3) Specific variables

“NO” : NO parameter is specified

If (value.length < 8) {// why is 8 less than 8? Length, displacement, or height? Oh,my God!! . }Copy the code

YES: Add variables

const MAX_INPUT_LENGTH = 8; If (value.length < MAX_INPUT_LENGTH) {// The maximum input length cannot be longer than.... }Copy the code

(4) Variable naming

NO: Naming is too verbose

let nameString;
let theUsers;
Copy the code

YES: Keep it short and concise

let name;
let users;
Copy the code

(5) Use descriptive variables (i.e., meaningful variable names)

NO: I don’t know what long code means

const address = 'One Infinite Loop, Cupertino 95014'; const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?) \s*(\d{5})? $/; SaveCityZipCode (address.match(cityZipCodeRegex)[1], // Address. Match (cityZipCodeRegex)[2] // See the code yourself);Copy the code

YES: Use variable names to explain long code

const address = 'One Infinite Loop, Cupertino 95014'; const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?) \s*(\d{5})? $/; const [, city, zipCode] = address.match(cityZipCodeRegex) || []; saveCityZipCode(city, zipCode);Copy the code

(6) Avoid using too many global variables

NO: continuously define global variables in different files

name.js window.name = 'a'; hello.js window.name = 'b'; time.js window.name = 'c'; // The loading order of the three files will cause the value of window.name to be different, and any changes you make to window.name may not take effect because you do not know if someone else resets the value of window.name in another description file. So as you add more files, it leads to a mess.Copy the code

You can choose to use only local variables. By (){} method.

If you do have a lot of global variables that need to be shared, you can use vuex, Redux or your own reference flux mode to write one.Copy the code

(7) Assignment of variables.

NO: There is NO backstop for evaluated variables.

const MIN_NAME_LENGTH = 8; let lastName = fullName[1]; If (lastname.length > MIN_NAME_LENGTH) {// Then you have successfully buried a hole in your code. Have you considered the situation if fullName = [' Jackie ']? So the program will explode as soon as it runs. Why don't you try it. . }Copy the code

YES: For the evaluated variable, do a good bottom line.

const MIN_NAME_LENGTH = 8; let lastName = fullName[1] || ''; // If fullName[1] is not available, it will not assign undefined, or at least a null character. Basically, the lastName variable type is still String, and all attributes in the String prototype chain can be used without error. It's not going to be undefined. if(lastName.length > MIN_NAME_LENGTH) { .... } In fact, there are many evaluation variables in the project, and each evaluation variable needs to be covered. let propertyValue = Object.attr || 0; // Because object.attr can be empty, we need to take a backstop. However, assignment variables do not need a backstop. let a = 2; // Because there is a bottom, so do not pocket. let myName = 'Tiny'; // Because there is a bottom, so do not pocket.Copy the code

2. Functional correlation

NO: The return value type cannot be known from the name

function showFriendsList() {.... } // Do you know if this returns an array, an object, true or false? Can you answer it? Can you answer me to invite you to eat pine crane house full banquet and please don't take it seriously.Copy the code

Yes: For functions that return true or false, it is best to start with should/is/can/has

function shouldShowFriendsList() {... } function isEmpty() {... } function canCreateDocuments() {... } function hasLicense() {... }Copy the code

(2) Functional functions should be pure functions

NO: Don’t make the output of a function variable.

Function plusAbc(a, b,c) {function plusAbc(a, b,c) {function plusAbc(a, b,c) {function plusAbc(a, b,c) {function plusAbc(a, b,c) {function plusAbc(a, b,c) { var c = fetch('.. /api'); return a+b+c; }Copy the code

YES: Function functions use pure functions. The input is consistent and the output is always unique

Function plusAbc(a, b,c) {// Return the same value of a, b,c. return a+b+c; }Copy the code

(3) Function parameter passing

NO: There is NO description for parameter transmission

page.getSVG(api, true, false); // What is true and falseCopy the code

YES: Parameter transmission is specified

Page. GetSVG ({imageApi: API, includePageBackground: true,})Copy the code

(4) Action functions should begin with a verb

NO: The intent of the function cannot be identified

function emlU(user) {
	....
}
Copy the code

YES: The function’s intent is obvious at the beginning of the verb

function sendEmailToUser(user) {
    ....
}
Copy the code

(5) a function to complete an independent function, do not mix a function of multiple functions

This is one of the most important rules in software engineering, and as functions need to do more, they become harder to write, test, understand, and compose. When you can pull out a function to do just one action, they will be easier to refactor and your code will be easier to read. If you follow this rule strictly, you will be ahead of many developers.

NO: A function contains multiple functions. In the end, I was killed by random fists (random fists (complex functions).

function sendEmailToClients(clients) {
  clients.forEach(client => {
    const clientRecord = database.lookup(client)
    if (clientRecord.isActive()) {
      email(client)
    }
  })
}
Copy the code

YES: functional disassembly,

Function sendEmailToActiveClients(clients) {// ForEach (email)} function isActiveClient(client) {const clientRecord = database.lookup(client) return clientRecord.isActive() }Copy the code

(6) Functional programming is preferred

NO: Program with a for loop

for(i = 1; i <= 10; A [I] = a[I] +1; }Copy the code

YES: Use functional programming

Let b = a.ap (item => ++item); Now almost all the for loop in javascript can be map, filter, find, some, any, forEach replaced by functional programming, etc.Copy the code

(7) Excessive use of if else..

No: If else too much

if (a === 1) {
	...
} else if (a ===2) {
	...
} else if (a === 3) {
	...
} else {
   ...
}
Copy the code

YES: Can be replaced with switch or array

switch(a) { case 1: .... case 2: .... case 3: .... default: .... } Or let handler = { 1: () => {.... }, 2: () => {.... }.3: () => {.... }, default: () => {.... } } handler[a]() || handler['default']()Copy the code

3. Use ES6 as much as possible, and if possible, new ES7 grammars (just list the most common new grammars, to be honest, some of the new grammars are not very common)

(1) Use arrow functions as much as possible

NO: Use traditional functions

function foo() {
  // code
}
Copy the code

YES: Use the arrow function

let foo = () => {
  // code
}
Copy the code

(2) Connection string

NO: Use the traditional + sign

var message = 'Hello ' + name + ', it\'s ' + time + ' now'
Copy the code

YES: adopts template characters

var message = `Hello ${name}, it's ${time} now`
Copy the code

(3) Use deconstruction assignment

NO: use traditional assignment:

var data = { name: 'dys', age: 1 };
var name = data.name;
var age = data.age;

var fullName = ['jackie', 'willen'];
var firstName = fullName[0];
var lastName = fullName[1];
Copy the code

YES: use structure assignment:

const data = {name:'dys', age:1}; const {name, age} = data; Var fullName = [' Jackie ', 'willen']; const [firstName, lastName] = fullName;Copy the code

(4) Use class as much as possible

NO: Inheritance is implemented using the traditional function prototype chain

Typical ES5 classes (functions) are less readable when it comes to inheritance, construction, and method definitions, and class is preferred when inheritance is required. There's too much code, so I left it out.Copy the code

YES: use ES6 class to implement inheritance

class Animal { constructor(age) { this.age = age } move() { /* ... */ } } class Mammal extends Animal { constructor(age, furColor) { super(age) this.furColor = furColor } liveBirth() { /* ... */ } } class Human extends Mammal { constructor(age, furColor, languageSpoken) { super(age, furColor) this.languageSpoken = languageSpoken } speak() { /* ... * /}}Copy the code



Github
Github
Github

Note: In addition to these artificial conventions, as mentioned earlier, for mechanical, you can use Babel, Eslint, Prettier to make sure code is formatted consistently.Copy the code

The resources

Blog.risingstack.com/javascript-… (JavaScript Clean Coding Best Practices)

www.zhihu.com/question/20… (How to write beautiful JavaScript code?)