When is it appropriate to use a semicolon?
Like some other modern languages derived from the C syntax, JavaScript syntax was designed to allow you to omit semicolons in almost all situations. I'd say use them always or use them never*. To use them "never" the long and short of it is that every statement goes on a new line and never begin a line with (
, [
, or `
.
However, to use them "never", you should definitely be using a linter such as JavaScript Standard Style or eslint with its built-in semi
rule to disable semicolons and its no-unexpected-multiline
rule which will make sure that you avoid the few gotchas such as the following:
a = b + c
(d + e).foo()
The above is interpreted as a = b + c(d + e).foo();
Note that by following the above rule and not beginning a line with (
this situation is prevented.
Another common example is the following:
return
{
hello: "world"
};
At a glance one may think this will be interpreted as returning an object, but it actually interpreted as return;
and the code to define the object after the return statement is unreachable. Again, by following the rule of not beginning a line with {
this is avoided.
- *Okay, okay, not never, but almost never.
Just prefix lines starting with [
, (
, or ` with a semicolon and you're (almost) golden*
Using the same example as another answer:
var x = { xx : "hello", yy : "world"}
(function () {
console.log("Hello World");
})();
We add a semicolon according to this rule:
var x = { xx : "hello", yy : "world"}
;(function () {
otherwise javascript thinks we're trying to call(
some function, or reference[
some array. This is simpler, easier to follow, and it's visually easier to spot. You also need semicolons in for
loops, but the .forEach
method is a cleaner and easier method. I'd confidently say this one rule covers 99% of the scenarios you need to use a semicolon in javascript/typescript.
Following this method, it's important to associate a newline with terminating a statement.
*This returns the venerable undefined
:
return
7
After return, there's a newline, and the browser inserts a semicolon, terminating the statement like this:
return; // this will return undefined.
7
Do this instead:
return (
7
)
Javascript is actually pretty smart with semicolons, there's an open paren, so no semicolon is inserted until the closing paren is found.
If you have a habit of putting semicolons everywhere and not knowing exactly when they are needed, you could read this for a several page long explanation: http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regarding
I admit most people will still just litter semi colons at the end of every line, but if you're new and just learning, this is the better approach.