Semicolons

A semicolon may be omitted in most cases when a line break exists. The following would work -

alert('Hello')
alert('World')

Here JavaScript interprets the line break as an “implicit” semicolon. That’s also called an automatic semicolon insertion.

In most cases a newline implies a semicolon. But “in most cases” does not mean “always”!

alert(3 +
1
+ 2);

The code outputs 6, because JavaScript does not insert semicolons here. It is intuitively obvious that if the line ends with a plus "+", then it is an “incomplete expression”, no semicolon required. And in this case that works as intended.

But there are situations where JavaScript “fails” to assume a semicolon where it is really needed.

It’s recommended to put semicolons between statements even if they are separated by newlines. This rule is widely adopted by the community. Let’s note once again – it is possible to leave out semicolons most of the time. But it’s safer – especially for a beginner – to use them.