It's a topic that could seem trivial at first sight, but it actually causes some controversy among JavaScript developers. Semicolons, yes or no? The s

Should you use semicolons in JavaScript?

submited by
Style Pass
2022-06-24 07:30:02

It's a topic that could seem trivial at first sight, but it actually causes some controversy among JavaScript developers. Semicolons, yes or no?

The syntax of JavaScript, just like many other languages, is based on the C programming language. In that language, semicolons are necessary to end a statement (i.e. an instruction.)

But JavaScript interpreters use Automatic Semicolon Insertion, a system that "inserts" semicolons before a line break in some circumstances. It doesn't literally insert it in the code, the interpreter acts as if there were a semicolon where ASI decides to.

The ASI system will add semicolons after "Nico" on line 1, after "Zerpa" on line 2, and after the closing parenthesis on line 3.

The problem is that omitting semicolons can lead to ambiguous code in some cases where ASI doesn't work as you may expect. Here's an example of this:

The code above doesn't work because ASI insert semicolons in an unexpected place: after the return keyword on the second line. On top of that, the JS interpreter gets confused. Due to the added semicolon, it mistakenly thinks the object is a block of code. That triggers a syntax error.

Leave a Comment