is inserted
only before }, after one or more newlines and at the end of program inputThis means that you can only omit the semicolon at the end of a line, a code block, and a program.
That is to say, you can write the following code
Insert
only if subsequent input tags cannot be parsedIn other words, semicolon insertion is an error correction mechanism. Look at the code and talk
a = b
f()
//Parsed into two independent statements
a = bf();//Error in analysis
So you have to pay attention to the beginning of the next statement to determine whether you can legally omit the semicolon.
(, [, , -, and / These five characters start the statement, then it is best not to omit the semicolon in front.
Give me an example
So for sentences starting with these five characters (, [, , -, and / , it is best not to omit the semicolon in front.
If you want to omit the semicolon, experienced programmers will follow this statement with a declaration statement to ensure that the parser parses it correctly. As shown below
Omitting semicolons causes script connection problems
//file2.js
(function () {
//......
})()
When the above two files are connected, they will be parsed as follows
So omitting the semicolon requires not only watching out for the next token in the current file, but also for any token that may appear after the statement after the script is connected.
To avoid parser parsing errors, you can prefix each file with an extra semicolon to protect the script from careless concatenation. If the first statement in the file opens with the five vulnerable characters mentioned above, you should add an additional semicolon prefix.
JavaScript syntax restricts production
JavaScript syntax restricts production: no line breaks are allowed between two characters.
Example:
Semicolon insertion rules for auto-increment and auto-decrement operations
The semicolon will not be automatically inserted as a separator at the head of an empty for loop statement
The while of the empty loop body also needs to display a semicolon, otherwise it will also cause parsing errors
To summarize
1. Semicolons are deduced only before the } mark, at the end of a line and at the end of a program
2. Semicolon
is deduced only if the following tag cannot be parsed
3. The semicolon
must not be omitted before statements starting with (, [, , -, and / characters
4. When linking scripts, explicitly insert semicolons
between scripts
5. Never break a line before the parameters of return, throw, break, continue, or --
6. A semicolon cannot be deduced as the head of a for loop or the delimiter of an empty statement