Problems with the following semicolon in JavaScript statements
The following is a detailed introduction to the semicolon problem behind statements in JavaScript through this article. This article introduces you to it in great detail. Friends who need it can refer to it.
JavaScript automatically adds points No. rules, there are 3
when there is a newline character (including multi-line comments containing newline characters), and the next token cannot match the previous syntax , the semicolon will be automatically added.
When there is }, if a semicolon is missing, it will be filled
When the program source code ends, if a semicolon is missing, Semicolons will be added.
Using my own JS syntax analysis tool JSinJS (https://github.com/kissjs/JSinJS), I found all the JS syntax that can appear in the first statement Marks (that is, the first set of Statement), they are:
["debugger", "try", "throw", "switch", "Identifier", "with", "return", "break", "continue", "for", "while", "do", "if", "new", "function", "(", "{", "[", "RegularExpressionLiteral", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral", "this", "!", "~", "-", "+", "--", "++", "typeof", "void", "delete", ";", "var"]
35 in total.
I also found all the grammatical markers that can appear before the semicolon (that is, the last set after removing the semicolon). They are
["--", "++", "IdentifierName", "]", ")", "}", "RegularExpressionLiteral", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral", "Identifier", "this", "debugger", "return", "break", "continue"]
, a total of 17.
35*17 = 595 combinations. In order to facilitate memory, I will discuss grammatical ambiguities in groups below. (Originally I used Excel to make a table, but the table is too big to post)
First of all, the statements starting with the following syntax tags are absolutely safe and will not cause any confusion with the previous line without a semicolon. Ambiguity:
var if do while for continue break return with switch throw try debugger ;
Next, let’s group the grammatical ambiguity caused by not adding semicolons:
First The first is that the two operators - and - appear at the end of the previous line. When the next line begins with the following, syntax ambiguity will occur:
function delete void typeof new null true false NumericLiteral StringLiteral RegularExpressionLiteral ( [ { Identifier -- - ~ !
Among them, function and delete are very commonly used statements at the beginning.
Especially and When -- is broken into one line alone, because the syntax rules of JS stipulate that the post-increment operation does not allow inserting a newline in the middle, so and -- will be regarded as the pre-increment and connected with the next line.
The second case is return as the end of the previous line. When the next line starts with the following, grammatical ambiguity will occur:
function delete void typeof ( [ { Identifier -- - ~ !
Also because the rules of JS grammar do not allow inserting a newline between return and the following value, so as long as there is a newline after return, it will be regarded as valid. number, which is often inconsistent with the user's expectations.
The third is the situation where the next line starts with and -, and the previous line ends with the following, which will cause grammatical ambiguity:
-- IdentifierName ] ) } RegularExpressionLiteral
Because there are few statements starting with or -, this situation is not considered dangerous.
The fourth situation is when the previous line ends with break or continue, and when the next line starts with Identifier, there will be grammatical ambiguity.
Five cases are when the next line starts with ( and [, and the previous line ends with the following, which will cause grammatical ambiguity:
-- IdentifierName ] ) } RegularExpressionLiteral StringLiteral NumericLiteral BooleanLiteral NullLiteral Identifier this
This situation is very dangerous (so hax’s article should mention this situation and write a semicolon before the statement). Almost all situations in the previous line will lead to unexpected behavior. result.
The sixth is that when the next line starts with RegularExpressionLiteral, the following ending of the previous line will cause/be interpreted as a division sign:
-- IdentifierName ] ) } RegularExpressionLiteral StringLiteral NumericLiteral BooleanLiteral NullLiteral Identifier this
Summary,
-
In the five statements of return, break, continue, post-increment, and post-decrement, the newline character can completely replace the semicolon.
var if do while for continue break return with switch throw try debugger Statements starting with several keywords, as well as empty statements, adding or not adding a semicolon in the previous line has little effect.
It is very dangerous not to add a semicolon after any expression statement or function expression statement, and the situation is extremely complicated.
Any statement starting with ( and [ without a semicolon in front of it is extremely dangerous.
The following examples are used Code introduction to the semicolon problem in JavaScript
Generally, lazy front-end programmers often encounter some inexplicable problems.
Today we will only discuss the We often encounter some problems about semicolons in JS. The JavaScript language can omit semicolons because it will not compile if there is a missing semicolon after the newline character. It will add a semicolon by default, but in In some specific cases, he will not add a semicolon by default. Now let’s briefly introduce a few things that need to be paid attention to.
In this case:
var x = 0 [x+1,x+2,x+3].forEach(function(){ console.log(x) })
这种情况下会导致程序无法正常运行。JavaScript在解析这段代码是并不会在var x = 0后换行。
在写代码时如果以一条语句以 ”(” ,"[" ,"+" ,"-" ,"/" 开始时通常在上一条语句不会默认添加分号的。所以在这种情况下尽量保持一下这种写法,在以这些字符开始时在行首添加一个分号,这样可以保证在别人更改上面代码时不加分号也不会影响以下代码运行。
var x = 0 ;[x+1,x+2,x+3].forEach(function(){ console.log(x) })
还有就是在涉及 return break continue 这种语句时尽量不要换行
return true; JavaScript会解析为 return; true; 在涉及 ++ 和 -- 这一系列运算时 在作为表达式的前缀或后缀时在换行是会有一定的问题,如下情况: var x = 0; var y = 0; x ++ y
JavaScript会解析为
x;++y; 而不是 x++;y;
虽然在JavaScript这门语言中 “;” 是可以省略不写的,但是还是建议大家每句代码后都跟上 “;” 养成这种良好的编码习惯,毕竟在大多语言中不带 “;” 的编码适不适用的。
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
The above is the detailed content of Problems with the following semicolon in JavaScript statements. 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











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

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.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

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.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

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 does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.
