Be Careful Where You Break Lines

Introduction

A number of dynamically typed programming languages don’t care about semicolons and treat them as optional syntax. JavaScript is not one of them. Semicolons are not optional. In some places, a semicolon is critical, while in other places, it’s more of a stylistic choice. However, if you leave out a semicolon where it’s required, JavaScript does not complain. That’s because JavaScript follows the philosophy that it’s more fun to take revenge than to complain.

📝Note: Merely placing a ; is not sufficient. We have to truly understand JavaScript’s automatic semicolon insertion (ASI) rules.

JavaScript’s automatic semicolon insertion (ASI) rules

The two main points of ASI rules are explained below with examples:

First rule

A valid program ends with a ;. If a given script does not end with a ;, JavaScript inserts a ; automatically. As the tokens are parsed from left to right, if an unexpected token is encountered and a line break separates the script from the previous token, then a ; is automatically inserted before the encountered token.

Example

For example, consider this code snippet:

Get hands-on with 1200+ tech skills courses.