Javascript automatically fills the semicolon rule

Before we talk about whether to write semicolons, let’s take a look at javascript’s rules for automatically filling semicolons.

The definitive guide to javascript says, “If a statement begins with a” (“, “[“,”/”, “+”, or “-“, it is most likely to be interpreted in conjunction with the previous statement. When writing javascript, if each statement is written on its own line, the semicolon is not required, but the next line may be merged with the next line if it encounters the symbol mentioned above. Statements starting with “/”, “+”, and “-” are relatively rare in implementation projects, while statements starting with “(” and” [” are quite common.

Situations that begin with “(” :

a = b
(function() {}) (12345)Copy the code

Javascript will interpret this as:

a = b(function() {

})();
1234Copy the code

Situations that begin with “[“

a = function() {} [1, 2, 3]. ForEach (function(item) {

});
1234567Copy the code

Javascript will interpret this as:

a = function() {} [1, 2, 3]. ForEach (function(item) {

});
12345Copy the code

Cases that begin with “/”

a = 'abc'
/[a-z]/.test(a)
123Copy the code

The expected result is true, but javascript interprets it as true and then returns an error:

A = 'ABC' / [a-z] /. The test (a); 12Copy the code

Cases that begin with a “+”

a = b
+c
123Copy the code

Javascript will interpret it as

a = b + c;
12Copy the code

Cases that begin with “-“

a = b
-c
123Copy the code

Javascript will interpret it as

a = b - c;
12Copy the code

If you wrap a line after keywords like return, break, continue, throw, etc., javascript fills in the semicolon at the line break. Such as:

return
{
    a: 1
}
12345Copy the code

Would be interpreted as:

return;
{
    a: 1
}
12345Copy the code

If the “++” or “-” operators suffix an expression, the expression should be on the same line; otherwise, it will be interpreted incorrectly

Such as:

x
++
y
1234Copy the code

Would be interpreted as:

x;
++y;
123Copy the code

Rather than

x++;
y;
123Copy the code

Should I write a semicolon

It’s not whether to write it or not but how do you write it and what do you do when you write it