search
HomeWeb Front-endJS TutorialIntroduction to the knowledge of Javascript semicolon rules (with examples)

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<p>May not meet the expected situation</p><pre class="brush:php;toolbar:false">const hey = 'hey'
const you = 'hey'
const heyYou = hey + ' ' + you

['h', 'e', 'y'].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. If there is any infringement, please contact admin@php.cn delete
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.