[Effective JavaScript note] 6th: Understanding the limitations of semicolon insertion

Source: Internet
Author: User

Semicolons can be omitted

JS can not force the addition of semicolons at the end of the statement. (recommended or added, do not add semicolons tend to appear difficult to find bugs)

function point (x, y) {

this.x=x| | 0;

this.y=y| | 0;

}

Point.prototype.isorigin=function () {

return this.x===0 && this.y===0

}

The above code can be run, because JS can automatically insert a semicolon, it is a program parsing technology. You can infer a semicolon that is omitted from certain contexts, and then effectively and automatically "insert" the semicolon into the program.

ECMAScript Standard carefully developed a semicolon insertion mechanism, can be easily transplanted.

A semicolon-inserted trap

Can not avoid learning its rules, by the effect of semicolon insertion, JS syntax has some additional limitations.

The principle of the insertion of semicolons the first rule

Semicolons are inserted only before the} tag, after one or more line breaks, and at the end of the program input.

Speaking of words, you can only omit semicolons in a row, a block of code, and where a program ends.

function Square (x) {

var n=+x

Return N*n

}

function Area (r) {R=+r;return Math.pi*r*r}

function Add1 (x) {return x+1}

Not legal.

function area (x) {r=+r return math.pi*r*r}

Rule number Two

Semicolons are inserted only when subsequent input tokens cannot be resolved.

Language: Semicolon insertion is an error correction rule.

A=b

(f ());

Can be parsed into a single statement, equivalent to:

A=b (f ());

No semicolon is inserted, because B (f ()) is a valid statement

A=b

f ();

Resolves to two separate statements

A=b f ();

Parsing error.

This means you must be careful when you omit the semicolon.

Characters that are problematic

5 clearly problematic characters require close attention: (, [, +,/.

Each character can be prefixed as an expression operator or a statement, depending on the context.

Be careful with statements that end in expressions, such as assignment statements. The next line starts with one of the 5 characters above, without inserting a semicolon.

The best thing to do is to (or [start with] the statement.

A=b

["R", "G", "B"].foreach (function (key) {

BAKCGROUND[KEY]=FOREGROUND[KEY]/2;

});

This sentence will be equivalent to

a=b["R", "G", "B"].foreach (function (key) {

BAKCGROUND[KEY]=FOREGROUND[KEY]/2;

});

Note: The bracket expression is a bit strange, JS allows a comma-delimited expression, often used to declare multiple variables, when the comma delimiter is used to assign a value, the operator always returns the value of the last expression.

+ 、-、/characters appear at the beginning of the statement is not common, but this is also the case.

+ No.:

10 is the result of immediate operation

Nan is the result of +undefined

/No.: Appears at the beginning of the statement is not actually a portal tag, but a regular expression

/error/i.test (str) &&fail ();

(&& is a short-circuit operation where the second operand is no longer evaluated if the first operand can determine the result.) )

The fail () operation is performed if the/error/i.test (str) result is true.

But if the situation is as follows

A=b

/error/i.test (str) &&fail ();

will be resolved to

A=b/error/i.test (str) &&fail ();

/be treated as a division operator.

To omit a semicolon, you can follow the statement with a declaration to ensure that the statement is not parsed incorrectly.

A=b

var x

(f ())

Refactoring may be replaced by someone

var x

A=b

(f ())

Although the above puts the Var statement ahead of time, these two pieces of code should be equivalent. However, in fact, a parenthesis followed by B will be parsed incorrectly to

var x;

A=b (f ());

As a result, you should also be careful where you omit the semicolon, and check to see if the tag that starts on the next line disables the automatic insertion of semicolons.

Or a method that adds an extra semicolon statement before the (, [, +,/character start).

A=b

var x

;(f ())

It's not going to go wrong with Var in advance.

var x

A=b

;(f ())

Another common scenario is that omitting semicolons can cause script connectivity problems. Each file may consist of a large number of function expressions.

File1.js

(function () {

.....

})()

File2.js

(function () {

.....

})()

When merging compression, the results are treated as

(function () {

....

}) (function () {

....

})();

When you omit a semicolon, be careful not only about the next tag of the current file, but also on any markup that might appear after the statement when the script is merged.

Can be defensive by adding a semicolon to the prefix to protect the script from the effects of merging.

File1.js

;(function () {

.....

})()

File2.js

;(function () {

.....

})()

After merging

;(function () {

....

}) ();(function () {

....

})();

The script runs correctly.

So don't omit any semicolons, is there no problem? Not necessarily, as

In the fight

return {};

When playing

Return

{};

Does not return an object because the sentence above is parsed into

return;

{}

;

3 separate statements.

This is the so-called JS Grammar restriction production, it does not allow a line break between two characters. If there is a newline, a semicolon may be inserted automatically.

As the return statement above. There must be no line breaks between the return keyword and its optional parameters.

Other constraint-generating formula:

    • Throw statement
    • Break or Continue statement with explicit tags
    • Post self-increment or decrement operator

The last one is to eliminate the following conditions

A

++

B

will be resolved to

A;++b;

Rule Three

Semicolons are not inserted automatically as delimiters in the header of the For loop empty statement.

You must explicitly include a semicolon in the head of the For loop.

for (Var i=0,len=20

I<len

i++

){

...

}

A syntax error will appear above.

The while of an empty loop also requires an explicit semicolon. Otherwise it will be an error.

function Infiniteloop () {while (true)}

Must be written

function Infiniteloop () {while (true);}

Tips
    1. Automatically insert semicolons only before the "}" tag, at the end of a line, and at the end of a program
    2. Inserts a semicolon only when the immediately preceding token cannot be parsed
    3. You must never omit a semicolon before a statement that starts with (, [, + 、-、/character
    4. When a script file is connected, a defensive semicolon is added at the beginning of the script
    5. Must not be wrapped before return, throw, break, continue, + +,--parameters
    6. Semicolons cannot be inserted automatically as a delimiter for a for loop's head or an empty statement

[Effective JavaScript note] 6th: Understanding the limitations of semicolon insertion

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.