Home  >  Article  >  Web Front-end  >  Introduction to the knowledge of Javascript semicolon rules (with examples)

Introduction to the knowledge of Javascript semicolon rules (with examples)

不言
不言forward
2019-03-25 14:21:032850browse

This article brings you an introduction to the knowledge of Javascript semicolon rules (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Take some time to figure out the semicolon rules in JS~~~Whether you like the mode with a semicolon at the end or omitting the semicolon

Scenarios where semicolons are allowed

Semicolons are generally allowed to appear at the end of most statements, such as do-while statement, var statements, expression statements, continue, return, break statement, throw, debugger, etc.

Chestnut:

do Statement while ( Expression ) ;

4+4;

f();

debugger;

has only one semicolon; which can represent an empty statement - it is legal in JS, such as ;;; can be parsed into three empty statements (empty statement)

Empty statement It can be used to assist in generating grammatically legal parsing results, such as:

while(1);

If there is no semicolon at the end, a parsing error will occur - the conditional loop must be followed by a statement

The semicolon will still appear Appears in the for loop for (Expression; Expression; Expression) Statement

Finally, the semicolon will also appear in the string or regular expression - indicating the semicolon itself

The semicolon can Omitted scenarios

In some scenarios, the semicolon can be omitted. The parser will automatically insert the semicolon as needed when parsing the statement. The approximate process can be understood as follows:

Omitted in writing=> Parser If it is found missing during parsing, it will not be parsed correctly => Automatically add semicolons

so it is necessary to clarify the scenarios where semicolons can be automatically inserted, and make it clear that semicolons will not be automatically inserted and will cause parsing errors

Rule 1: When the next token (offending token) and the currently parsed token (previous token) cannot form a legal statement, and one or more of the following conditions are met, a semicolon will be inserted before the offending token:

  • offending token and previous token are separated by at least one newline character (LineTerminator), and the effect of semicolon insertion is not to be parsed as an empty statement (empty statement)
  • offending token is}
  • previous token is), and the inserted semicolon will be parsed as the terminating semicolon of the do-while statement

There is also a higher priority condition to consider: if inserted The semicolon will be parsed as an empty statement, or one of the two semicolons at the beginning of the for statement, and no semicolon will be inserted (except for the terminating semicolon of the do-while statement)

Rules 2: When the parsing reaches the end of the source code file (input stream), a semicolon will be automatically added to mark the end of the parsing

Rule 3: Statements that conform to restricted production syntax - difficult to translate and incomprehensible You can directly look at the chestnut. The main description of this situation is: the occurrence of a newline character where a newline character should not appear causes the insertion of a semicolon, causing the meaning of the original statement to change

If the following conditions are met at the same time, it will be automatically inserted before the offending token A semicolon:

  • offending token and previous token form a syntax restricted production statement
  • offending token appears in the [no LineTerminaator here] part of the restricted production statement description (the token would be the first token for a terminal or nonterminal immediately following the annotation “[no LineTerminator here]” within the restricted production )
  • There must be at least one newline character (LineTerminator) between offending token and previous token

Restricted production includes and only the following:

UpdateExpression[Yield, Await]:
  LeftHandSideExpression[?Yield, ?Await] [no LineTerminator here] ++
  LeftHandSideExpression[?Yield, ?Await] [no LineTerminator here] --

ContinueStatement[Yield, Await]:
  continue;
  continue [no LineTerminator here] LabelIdentifier[?Yield, ?Await];

BreakStatement[Yield, Await]:
  break;
  break  [no LineTerminator here]  LabelIdentifier[?Yield, ?Await];

ReturnStatement[Yield, Await]:
  return;
  return  [no LineTerminator here]  Expression  [+In, ?Yield, ?Await];

ThrowStatement[Yield, Await]:
  throw [no LineTerminator here] Expression [+In, ?Yield, ?Await];

ArrowFunction[In, Yield, Await]:
  ArrowParameters[?Yield, ?Await] [no LineTerminator here] => ConciseBody[?In]

YieldExpression[In, Await]:
  yield [no LineTerminator here] * AssignmentExpression[?In, +Yield, ?Await]
  yield [no LineTerminator here] AssignmentExpression[?In, +Yield, ?Await]

Simple summary:

When using the a statement, the variable and must be on the same line, otherwise a semicolon will be inserted before Different semantics

If return throw yield continue break is followed by a newline, a semicolon will be added automatically

There should be no newline character before => of the arrow function

Chestnut & may not meet the expected situation

Conform to the expected situation

// 相当于 42;"hello"
42
"hello"

// offending token 是 }
if(x){y()}

// previous token 是 ) 且插入分号是 do while 语句的结束
var a = 1
do {a++} while(a<100)
console.log(a)

//  不会解析成 b++ 因为 b和++之间存在换行符,会在 b 之后自动插入分号
a = b
++c

May not meet the expected situation

const hey = &#39;hey&#39;
const you = &#39;hey&#39;
const heyYou = hey + &#39; &#39; + you

[&#39;h&#39;, &#39;e&#39;, &#39;y&#39;].forEach((letter) => console.log(letter))

You will receive the error Uncaught TypeError: Cannot read property 'forEach' of undefined , because the connection between you and ['h', 'e', ​​'y'] can hit the legal syntax, so a semicolon will not be automatically inserted between them - inconsistent with expectations, JS tries to parse the code as:

const hey = 'hey';
const you = 'hey';
const heyYou = hey + ' ' + you['h', 'e', 'y'].forEach((letter) => console.log(letter))

Look at another situation:

const a = 1
const b = 2
const c = a + b
(a + b).toString()

will cause TypeError: b is not a function error, because it will be interpreted as:

const a = 1
const b = 2
const c = a + b(a + b).toString()

Except Except for the do while statement, there will be no other situations where a semicolon is inserted as an empty statement, or as two necessary semicolons at the head of a for statement:

if (a > b)
else c = d

for (a; b
)

None of the above are legal JS statements and will cause an error.

Therefore, every semicolon in the following chestnuts cannot be omitted! !

// for循环没有循环体的情况,每一个分号都不能省略
for (node=getNode();
     node.parent;
     node=node.parent) ;

Look at another example with detailed comments:

var         // 这一行不会插入分号 ,因为 下一行的代码不会破坏当前行的代码  
    a = 1   // 这一行会插入分号   
let b = 2   

// 再比如这种情况,你的原意可能是定义 `a` 变量,再执行 `(a + 3).toString()`,
// 但是其实 JavaScript 解析器解析成了,`var a = 2(a + 3).toString()`,
// 这时会抛出错误 Uncaught TypeError: 2 is not a function
var a = 2
(a + 3).toString()

// 同理,下面的代码会被解释为 `a = b(function(){...})()`
a = b
(function(){
...
})()

The above are all cases where rule 1 is not hit and a semicolon is not inserted, causing the parsing to be inconsistent with expectations

Look at an example based on rule 3:

(() => {
  return
  {
    color: 'white'
  }
})()

is expected to return an object containing the color attribute, but in fact a semicolon will be inserted after return, resulting in undefined being returned in the end. You can place it immediately after return Curly braces {:

(() => {
  return {
    color: 'white'
  }
})()

Best practice for omitting semicolons

不要使用以下单个字符 ( [ / + - 开始一行 , 会极有可能和上一行语句合在一起被解析( ++ 和 -- 不符合单个 +、- 字符)

注意 return break throw continue 语句,如果需要跟随参数或表达式,把它添加到和这些语句同一行,针对 return 返回内容较多的情况 (大对象,柯里化调用,多行字符串等),可以参考规则1,避免命中该规则而引起非预期的分号插入,比如:

return obj.method('abc')
          .method('xyz')
          .method('pqr')
 
return "a long string\n"
     + "continued across\n"
     + "several lines"
 
totalArea = rect_a.height * rect_a.width
          + rect_b.height * rect_b.width
          + circ.radius * circ.radius * Math.PI
后缀运算符 ++ -- 需要和操作变量在同一行使用

当然大部分工程化情况下,我们最终会配合Eslint使用带分号或省略分号规范~~~

本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的JavaScript视频教程栏目!

The above is the detailed content of Introduction to the knowledge of Javascript semicolon rules (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete