JS Magic Hall: ASI (automatic semicolon insertion mechanism) and front semicolon

Source: Internet
Author: User
Tags integer division

First, preface

Tonight in the eyes of the people to see the front-end technical experts-He Shijun on the JavaScript sentence should be added semicolon? "The answer, let me once again see Daniel's style, really admire extremely." But pure admiration is not enough to repay him such excellent words, must understand the meaning of the text and the principle behind it deserves it!

Prior to this we need to understand the ASI (automatic semicolon insertion mechanism) first.

Second, Automatic semicolon insertion (ASI, automatic semicolon insertion mechanism)

Main reference: http://justjavac.com/javascript/2013/04/22/automatic-semicolon-insertion-in-javascript.html

The monkeys who work in C # and Java know that semicolons are used as eos,end of statement, and must be semicolon-otherwise the compilation will not pass. But JavaScript allows us to omit semicolons due to the existence of the ASI mechanism. The ASI mechanism does not say that the parser automatically adds the semicolon to the code in the parsing process, but that the parser, in addition to the semicolon, will use a certain rule as the basis for the segmentation, thus guaranteeing the correctness of the parsing.

First these rules are based on two points:

1. Based on the act of Exchange;

2. The parser will try to incorporate the new row into the current row, and the new row will be treated as a stand-alone statement only if the ASI rules are met.

The rules of ASI

1. The new line is merged into the current row will constitute an illegal statement, automatically inserting semicolons

if (11console.log (a)//  equivalent to if(110  1; Console.log (a);

2. Automatically insert a semicolon after Continue,return,break,throw

return1}//  equivalent to return1};

3. + + 、--suffix expression automatically inserts a semicolon at the beginning of a new line

a+c// is equivalent to A; ++c;

4. The last statement of the code block automatically inserts a semicolon

1 }//  equivalent to 1; }

The rules of the No ASI

1. New line to ( start

var 1 var b = A (a+b). toString ()//  will be resolved to call function A with a+b as the entry parameter. Then call the function to return the value of the toString function var1var b =a (a+b). ToString ()

2. New line to [ start

varA = ['A1','A2']varb =a[0,1].slice (1)//will be parsed first to get a[1], then call A[1].slice (1). //because the comma is inside [] and is not parsed into an array literal, it is resolved to an operator, and the comma operator executes the left expression first, then executes the right expression and evaluates to the right expression as the return valuevarA = ['A1','A2']varb = a[0,1].slice (1)

3. New Line / start

var 1 var b = a/test/. Test (b)/ // /will be resolved to the integer division operator instead of the starting symbol for the regular expression literal. In the browser, there will be more than one before the test. var1var b = a/test/. Test (b)

4. New lines start with + , - , % and *

var 2 var b = a+a//  will parse the following format var2var b = A + a

5. New line with , or . start

var 2 var b = a.tostring () console.log (typeof  b)//  resolves to var 2 var b = a.tostring () console.log (typeof B)

Here we have a certain understanding of the ASI rules, and another interesting thing is that " empty statement ."

 //  three empty statements   //  only if conditional statements, statement blocks are empty statements.  //  unless conditional statements are implemented  if  (1  >2 ); else   Console.log ( "  2 is greater than 1 always!     //  only the while condition statement, the loop body is an empty statement.  var  a = 1  while  (++a < 100 ); 

Third, the front semicolon

Reiterate the function of the semicolon-as the assertion (EOS) of the statement, in order for the parser to parse the program correctly. Now that there is the ASI mechanism, why are there so many teams of code specifications that also stipulate that a semicolon must be written? There are three reasons: 1. Because there is no ASI situation, too lazy to remember these special cases; 2. Team of engineers need to take into account the development of both front and back (bitter force like me ~), the latter in Java, C # or PHP, keep the code specification close to the management cost is lower; 3. That's the old norm, and there's no need to change it now.

For the code compression tool to be problematic after omitting the semicolon, JSLint will warning the code without the semicolon, He Shijun has explained it in detail in the reply. Therefore, the semicolon is a purely personal and team preferences, of course, can also be mixed use (below to borrow a picture of Daniel @ Plateau)

For my this can be less knock on the keyboard, can not use the mouse on the big lazy, naturally added to the "no semicolon Party" embrace, the precondition is to remember the rules to deal with the situation of no ASI:

in the ([/+- ] preceded by a semicolon (the normal wording will not appear in the ., *% as the beginning of the statement, so just remember the first 5, you can lazy and lazy oh)

Then the code structure is clearer with reasonable indentation and blank lines (Coffeescript is not the case?!) )

Example:

;(function (exports, undefined) {varGetkeys =Object.getownpropertyname&&Object.getOwnPropertyName.bind (Object)||function (obj) {varKeys = []           for(varKeyinchobj) Keys.push (key)returnKeys}vareach = Exports.foreach = Exports.each =function (Arraylike, FN, CTX) {if(Arraylike = = undefined)return       varIsobj = Arraylike.length!== +arraylike.length, Keys= Isobj?Getkeys (arraylike): Arraylike, Len=keys.length, idx for(vari =0; IDX = isobj? Keys[i]: I, i < Len; ++i) Fn.call (CTX, IDX, Arraylike[idx])}} (NewFunction ('return This')(),void 0)) ForEach ({'s':1,'C':2}, function (I, item) {Console.log (i+'  '+Item)}) ForEach ([1,2], function (I, item) {Console.log (i+'  '+Item)})

Now we can safely do "no semicolon party" Oh!

Iv. Summary

The ASI once again demonstrates the high degree of freedom of JavaScript syntax, so the code specification is so important for team development. The degree of mastery of grammar also reflects the technical level of the front-end engineer from another aspect. It looks like we have to keep working on it!

Respect the original, reprint please specify from: http://www.cnblogs.com/fsjohnhuang/p/4154503.html ^_^ fat son John

V. Other references

Http://justjavac.com/javascript/2013/04/22/automatic-semicolon-insertion-in-javascript.html

Http://inimino.org/~inimino/blog/javascript_semicolons

Http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regarding

JS Magic Hall: ASI (automatic semicolon insertion mechanism) and front semicolon

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.