Why you should add semicolons
Take a look at this example:
a = b + c (d + e).toString()
This code throws an error because the line
c to be a function call with
d + e as an argument.
Next example, two statements on one line
i++ a = b + c
This one is pretty obvious. If you have two statements on a single line, semicolons are required regardless of your preferences. Automatic semicolon insertion has no way of knowing if a semicolon is needed in the above example. This code results in an error.
Automatic semicolon insertion has a bunch of edge-cases where it either fails or at the very least behaves unexpectedly. Adding in semicolons yourself makes sure that your code runs exactly as you expected it to.
When should you leave semicolons out
The main reasons for not inserting semicolons cited in arguments tend to be:
- It’s more readable
- It encourages developers to better understand the language
The first is just personal taste. I personally think adding semicolons produces more readable code, but that is also personal taste.
That second argument is often accompanied by a good deal of gatekeeping. If you don’t know how this works, you shouldn’t be allowed to write code professionally. That is not a good reason to leave out semicolons.
So, when is? Well, most of the issues mentioned with automatic semicolon insertion can be mitigated by enforcing the use of linters and formatting tools like Prettier. So, if that’s in place and your team prefers leaving semicolons out, you should follow the rest of your team. The code you write as a team should look like it was written by one person.
To sum up
Adding semicolons yourself results in cleaner code that is slightly less error-prone.
Leaving semicolons out is not that big of a deal if you have the right tools.