

This happens because the 4th rule of ASI states that if a return statement is encountered on its own line, a semicolon is inserted. Perhaps the most common example of this is the for loop.įor example: const numbers = įor (let i = 0 i 1). If you have two JavaScript statements on the same line, you have to separate them by semicolons. Required Usage: Separate Two Statements on the Same Line Guide to Using Semicolons in JavaScriptīefore discussing the pros and cons of using semicolons, you need to understand how how they are used in the first place. Console.log (function2 ()) Output: undefined It is quite surprising that function2 () returns undefined without any error being thrown. Last but not least, you are going to see a list of pros and cons of using semicolons.Īt the end of this guide, you should be able to decide if you want to use semicolons or not. Then you are going to learn how the automatic semicolon insertion works behind the scenes. In pre-ES2015 targets, the most faithful emit for constructs like for/of loops and array spreads can be a bit heavy. This is a comprehensive guide on how to use semicolons in JavaScript.įirst, we are going to walk through the rules of using the semicolons in JavaScript code. For more details on the change, see the pull request here. But there are also great reasons why you should not use them.

There are good arguments that support using semicolons. For example, when you configure to add semicolons to all code, you can only add semicolons to those necessary places when writing, and then VS Code will format. Using semicolons always causes a debate in the JavaScript community. So there is no definitive answer as to whether you should use a semicolon or not.

However, there are some situations in which omitting a semicolon can lead to unwanted consequences. There is a technical reason: Semicolons are generally only inserted when the code would not compile without it.
