简体   繁体   中英

May I omit every semicolon at the end of line in all version (if any) of JavaScript?

I'm learning JavaScript and I somehow figured out that I may skip typing ; at the end of a line, as long as there's only one statement in that line. In fact I'm used to this a bit; I developed a simple iOS app with Swift which supports this kind of syntax too.

But what I'm wondering is whether there's a specific version or something of JavaScript which does not allow programmers to omit the last semicolon. Lots of languages have had changes in syntax; so I guess JavaScript might have this kind of problem.

Note that while all versions of JavaScript support ASI, there are pitfalls of ASI that will mean you can't get rid of all semicolons.

For example, the following will not work as you might expect:

function foo() { return [2, 3] }

var x, y, i, j
j = 2
i = j
[x,y] = foo()

You might expect that i , j , and x will equal 2, and y will equal 3, which is what would happen if every line were semicolon-terminated. However, that is not the case.

In fact, i is [2,3] , while x and y are undefined . When ASI ran on that section of code, it interpreted the final two lines as a property access:

i = j[x,y] = foo()

while it was probably intended to be a destructuring operation:

i = j;
[x,y] = foo();

A method to get around this is to use "defensive semicolons" before any line beginning with [] or () that is not intended to be treated as the continuation of the previous statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM