JavaScript programming style (writing habits)


The “grammar” of a programming language should be followed by every developer; The “programming style” is free to choose.

Assuming that there are 100 members in the team, and then each member’s coding style is different, and there is no clear writing specification in the team, you should not fight or spit fragrance in your heart during code review Therefore, there are many lint tools in the community to help teams standardize their writing habits, such asESLintPrettierwait…

The choice of “programming style” should not be based on personal hobbies, familiarity, typing workload and other factors, but should consider how to make the code as clear and readable as possible and reduce errors. What you choose is not the style you like, but a style that can clearly express your intention.

Recommend JavaScript authorityDouglas CrockfordA speech by(Youtube)。

1、 Brace position

Rule 1: curly braces indicating the beginning of the block, do not start another line.

Most programming languages use braces{}Represents a block, and so does JavaScript.

There are two common ways to write:

// bad
  // ...
// good
block {
  // ...

Due to JavaScriptAuto insert semicolon(automatic semiconductor insertion, ASI) mechanism, resulting in some undetectable errors.

Therefore, in principle, the latter is recommended:The opening brace follows the keyword

For example:

  key: 'value'

The original intention of the above code is to return an object, but the actual return value isundefined。 Because of ASI, the JavaScript parser willreturnInsert semicolon after;, since the semicolon is a terminator, the parser thinks the statement is over.

similarreturnIn ASI, it is calledrestricted production。 It includes the following syntax, which cannot wrap lines:

  • Postfix Expression ++and--
  • return
  • continue
  • break
  • throw
  • Arrow function of ES6 (line breaks are not allowed between parameters and arrows)
  • yield

There is no need to memorize these, because according to the general writing habit, few people will wrap lines like this. If so, hit Si it.

2、 Position of parentheses

Parentheses have two functions in JavaScript. One is to call a function, and the other is to group different values. We can distinguish between two different parentheses with spaces.

Rule 2: when calling a function, there is no space between the function name and the left parenthesis.

// bad
foo (bar)

// good

Rule 3: there is no space between the function name and the parameter sequence.

// bad
function fn (foo) {
  // ...

// good
function fn(foo) {
  // ...

Rule 4: there is a space between all other syntax elements and the left parenthesis.

// bad
return(foo + bar)

// good
return (foo + bar)

In the above example, you’d better remove the parentheses. In fact, it doesn’t need parentheses in this sentence. This is just an example.

I believe many people despise the above three suggestions. 2021, then give it toPrettierDeal with it.

3、 Do not omit semicolons

Rule 5: don’t omit the semicolon at the end of the sentence.

Actually, I’m biasedsemicolon-lessStyle, I think the whole article is 99% less semicolons, which will look much simpler.

I wrote an article about automatic semicolon insertion:Detailed explanation of JavaScript ASI mechanism

But at this time, some people will cite similar examples to oppose the “semicolon free party”:

a = b
(function () {
  // ...

Due to the ASI mechanism, the JavaScript parser will see this:

a = b(function () {
  // ...

Yes, so we can’t get the expected results. But as a qualified semicolon less coder, if a statement is based on([/+-At the beginning, we will actively type a semicolon at the beginning of the line of the statement to avoid semicolons;To avoid non overdue results or errors generated by ASI mechanism.

In the actual project/+-There is very little code at the beginning of the line,([Also less.

If you say it’s easy to forget to type a semicolon, it means you’re not a qualified “no semicolon party”. Just knock the semicolon!Perhaps most people are more likely to forget, so they have the recommended writing method of “don’t omit the semicolon at the end of the sentence”. (it’s a compromise in which the minority obeys the majority)

For those who blindly deny semicolon less without thinking, I still give a big sentence:All intuitive “semicolons of course” are conservative, thoughtless and hasty conclusions.

4、 With statement

Rule 6: do not usewithsentence.

with (obj) {
  foo = bar

The above code may produce four running results: = bar =

foo = bar

foo =

All of the above four results can occur, depending on whether different variables are defined. Therefore, it is not recommended to usewithsentence.

5、 Equality and strict equality

Rule 7: try not to use the equality operator (= =), but the congruence operator (= =).

Previously, I wrote an article on equality operator and congruence operator:JavaScript equality comparison details, the article begins with the following sentence:

Always use 3 equals unless you have a good reason to use 2.

The main reason is that when using the equality operator to compare two operands of different types, JavaScript will “secretly” carry out type conversion internally.

0 == '' // true
2 == true // false
0 == '0' // true
false == '0' // true
' \t\r\n ' == 0 // true

6、 Merging of statements

Some developers pursue “excessive” simplicity and like to combine statements for different purposes.

For example, the primitive sentence is:

a = b
if (a) { ... }

He likes to write as follows:

if (a = b) { ... }

Although one line of the statement is missing, its readability is greatly reduced, and it will cause misreading, making others mistakenly think that this line of code means:

if (a === b) { ... }

In another case, some developers prefer to assign multiple variables in the same row:

//Non strict mode
var a = b = 0

It may think that the above code is equivalent to:

var a = 0, b = 0

But it’s not. Its real effect is as follows:

//This refers to the non strict mode (an error will be reported in the strict mode, and the writing of this default global variable is not allowed)
b = 0
var a = b

Therefore, merging statements for different purposes into one line is not recommended.

7、 Variable declaration

In JavaScript, there is a very famousVariable promotionHoisting)I believe we all know the concept.

No matter what happens in our actual project, as a qualified or unqualified jser, we should understand what promotion is, okay. I wrote an article before:Gain insight into the process of JavaScript from precompiling to parsing execution。 (PS: it was not written well at the beginning. It is suggested to see MDN or ECMAScript standard)

Just one sentence:

First declare, then call.

And it’s 2021. Don’t use it as much as possiblevarYes, use itletconstLet’s go. As for compatibility, you can rest assuredBabelCome on!

// bad
if (!obj) {
  var obj = {}

// good
var obj
if (!obj) {
   obj = {}

In order to avoid possible problems, it is better to put variable declarations at the head of the code block.

// bad
for (var i ...) { ... }

// good
var i
for (i ...) { ... }


Rule 9: all variable declarations are placed at the head of the function.

Rule 10: all functions are defined before use.

8、 Global variable

The biggest syntax disadvantage of JavaScript may be that global variables are readable and writable for any code block. This is very disadvantageous to the modularization and reuse of the code.

Rule 11: avoid using global variables; If you have to use it, use uppercase letters to represent the variable name, such asUPPER_CASE

9、 New keyword

JavaScript uses the new keyword to generate a new object from the constructor.

var obj = new myObject()

The problem with this approach is that you forget to addnewkeyword,myObject()InternalthisThe keyword will point to the global object (in strict mode)thisbyundefined)As a result, all variables bound to this become global variables.

Rule 12: do not usenewKeywords, use insteadObject.create()To create a new object.

Rule 13: the function name of the constructor is written in initialcap; All other function names are lowercase.

Of course, the initial capital of the constructor name is just a conventional way of writing, which does not affect the actual operation. Like eslint, there is onenew-capRules to check this writing.

10、 Self increasing and self decreasing operators

Self increasing++And self subtraction--Operators, placed before or after operands, have different return values and are prone to errors.

To tell you the truth, I still often can’t remember these two things clearly. Sometimes, you have to check it to confirm whether it is expected to run.

So I also use+= 1or-= 1To replace it. Eslint also has a ruleno-plusplusTo limit this writing.

//  bad

// good
i += 1

It is said that the following code fragments appear in the source code of a JS Library:


//How to look at it, a more reasonable way to write it should be:
i += 2


Rule 14: do not use self augmentation(++)And self subtraction(--), use+=and-=Replace.

In fact, my habit is to only allowforoffinal-expressionUse self increment or self decrement, and others are not allowed, so the eslint rule can be written like this.

/* eslint no-plusplus: ["error", { "allowForLoopAfterthoughts": true }] */
for (let i = 0; i < 10; i++) {
  //The above final expression allows self increment and self decrement, but the loop body itself does not



To sum up, it can be summarized into one sentence:How do you like it

It’s 2021. The project has inherited eslint and prettier. Many of the above problems have basically been solved for you. But we should understand the reasons behind it, right.

For me with obsessive-compulsive disorder, I have to inherit itCSScomb, to sort CSS. You can see my next democsscomb-mini

reference resources

Recommended Today

Basic operations of Sqlalchemy connecting to MySQL database #!/usr/bin/env python3.8.6 # _*_ coding: utf-8 _*_ # Description: # Author: qiaoxiaohang # Date: 2022/4/8 from config import DB_URI from sqlalchemy import create_engine #Todo creates the engine and links the database # engine = create_ Engine (db_uri) # create engine # conn = engine. Connect() # link # result = conn.execute(‘select * from boo’) […]