


Introduction 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<100) console.log(a) // 不会解析成 b++ 因为 b和++之间存在换行符,会在 b 之后自动插入分号 a = b ++c
May not meet the expected situation
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Lambda expression is an anonymous function without a name, and its syntax is: (parameter_list)->expression. They feature anonymity, diversity, currying, and closure. In practical applications, Lambda expressions can be used to define functions concisely, such as the summation function sum_lambda=lambdax,y:x+y, and apply the map() function to the list to perform the summation operation.

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Real-time collaborative editors have become a standard feature of modern web development, especially in various team collaboration, online document editing and task management scenarios. Real-time communication technology based on WebSocket can improve communication efficiency and collaboration effects among team members. This article will introduce how to use WebSocket and JavaScript to build a simple online collaborative editor to help readers better understand the principles and usage of WebSocket. Understand the basic principles of WebSocketWebSo
