86

I know that JavaScript (and thus TypeScript) support the omission of semicolons in many cases. Nevertheless I want to add semicolons to be unambiguous as suggested in TypeScript Deep Dive

However I cannot find a guide that lists where to use semicolon. For example look at the following code

class Person {
  private name: string; // A

  constructor(name: string) {
    this.name = name;
  }; // B

  public add = () => {
    return "C";
  }; // C
}; // D

I'm fairly sure to use a semicolon at A. But what about B, C, D and all the other cases not covered by my example?

I'm not asking where to omit semicolon but where to add them. An answer like always does not fulfill my needs since I cannot add a ; after public. I want to know where exactly to put semicolon.

0

4 Answers 4

66

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.

If you are using typescript (hopefully you are, it's 2023 now), and forget a semi, using my first example, you'll get this error:

lkasdljkasfldjk

5
  • 19
    The question asks about TypeScript, but all your references are to JavaScript. Avoiding semicolons in TypeScript is perfectly safe as the compiler will consider invalid code the one that would otherwise have given problems at runtime.
    – DanielM
    Sep 16, 2017 at 20:04
  • Indeed I'm basing this all on my knowledge of javascript. Thank you for pointing out the TS compiler will throw a compile time error. Going to edit my answer.. Jul 20, 2019 at 21:36
  • This answer I wrote was motivated to bringing cleaner code into the future, but for most situations at most companies, you probably want to use semi-colons.. python is really picking up steam, and if we CAN be more like python, by not using semi-colons, then we SHOULD. If you paste my 1st example code into typescriptlang.org/play, I find the error pretty hard to understand (although I haven't had significant TS experience, so this may be a factor). Jul 20, 2019 at 21:55
  • So let's assume you use a linter like eslint for better error messages. The safest option is to set your semis (semicolon) rule to "always" - and then follow the error messages. Some developers may disagree, but "always" using semi-colons is the status quo as far as I know. Although, using semi-colons strictly only where necessary is a slightly lower cognitive load IMO, once you are adjusted to it. Jul 20, 2019 at 22:09
  • 2
    If you follow my suggestion here, YOU REALLY SHOULD set the eslint rules "no-unexpected-multiline": "error", "semi": ["error", "never", { "beforeStatementContinuationChars": "always" }], "semi-style": ["error", "first"], and it will actually enforce putting semis before opening parens/brackets/etc and disallow semi's at end of line. Jul 21, 2019 at 1:26
22

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.
3
  • 1
    Downvoted, because of two errors: 1. Note that by following the above rule.. nothing follows. 2. following the rule of not beginning a line with { This parantheses is not metnioned in your ruleset.
    – angabriel
    May 17, 2021 at 11:52
  • 2
    @angabriel Thanks for your feedback. Lets make it better! I could not figure out what you mean by #1. The statement you reference clearly does have a continuation. For your second point, while JavaScript Standard Style's configuration /does/ have protection against the "gotchas", if you're using raw eslint there isn't a rule by default. So I added a note about the need to use no-unexpected-multiline when using eslint to prevent the "gotchas". Let me know what else we can do to improve this answer for the community. May 18, 2021 at 21:19
  • 1
    Nice. After your editing I understand both of your arguments. The return example is kind of a special case though: The "rule" sais to only avoid ( and [ parantheses in the beginning of a newline, but in combo with a trailing return statement one should also avoid { on the next line. Thank you for keeping the quality up! Upvoted ;)
    – angabriel
    May 18, 2021 at 23:33
15

TL;DR: Always

Keep in mind: better safe than sorry

You should probably place them all the time. You don't need to place them in order for TypeScript to work, but you will avoid errors by doing so. ASI (Automatic Semicolon Insertion) works quite well most of time, but not always. Do you really want to run into a problem just because you didn't put a semicolon, and you keep overlooking the mistake? (Depending on your IDE, the mistake might actually be caught). But consider this perfectly valid Javascript.

 var x = { xx : "hello", yy : "world"}
 (function () {
     console.log("Hello World");
 })();

This is valid javascript (and thus valid typescript). This code will actually give an error. Uncaught TypeError: (intermediate value)(intermediate value) is not a function(…).

Which could be avoided by just placing a semicolon after the first line. You don't need it there, and if the next line wasn't that function line, it would probably work correctly. But you want to take that risk? It seems like taking the risk for mistakes over one extra character is not worth it to me. Plus, after a while, you just get used to place semicolons at the end of a line anyway;

Think of your colleagues

Another reason you might want to use them all the time is in the case of code changing. Your colleague might have to change your code - and in doing so thinks that the ASI will keep working even with his code change. Imagine that this is not the case, and that his change actually makes ASI do something wrong. Is it really worth that headache for your colleague? If he changes enough of your code and then suddenly runs into a lot of errors, he might be rather confused if he does not know the exact way in which ASI is working. You could save a potential colleague quite a bit of (unneccessary) work by just putting them everywhere.

10
  • 1
    Yes but when is always? I cannot add a semicolon after everything that would introduce syntax errors (and be indefinitely large since I would add ; after ;). I'm not asking whether I should omit semicolon. I'm asking where to put them.
    – ooxi
    Aug 8, 2016 at 8:49
  • 3
    What's a statement? Is a for-loop as statement (it's not an expression thus I guess it is). I've never seen anybody add ; after the block of a for loop
    – ooxi
    Aug 8, 2016 at 8:53
  • 44
    This is an irrational opinion steeped in habit and supported by the wholly incorrect interpretation of how ASI works. The omission of semicolons is no more risky than adding one where it is not intended. This myth is just so incredibly widespread that sadly it's still conventional wisdom. Oct 16, 2016 at 17:59
  • 3
    The piece of code that you have shown is not valid TypeScript, just try it out in their playground -- typescriptlang.org/play. As a consequence, you do not need semicolons in TypeScript, and you should therefore not use them unless you are some kind of semicolon fanatic.
    – DanielM
    Aug 28, 2017 at 17:52
  • 5
    I work with Typescript, Java and Perl and frequently jump from one code base to the other. I find it easier to always use semicolons as a consistent habit in the three languages.
    – Chris
    Oct 23, 2017 at 13:55
10

You need to watch that you do not inadvertently add semi-colons but the best way to avoid that self-inflicted bug is not to use them except where required by the language.

This bug is as likely as the one and only case where omitting semicolons might not capture your actual intent:

for(int i = 0; i < count; i++); do()

There is one situation where your intent might be ambiguous, with the unusual style of starting a line with a ( or a [ character, since the newline doesn't terminate the statement in that case. The vast majority of the time it's precisely what you want, it's obvious when it's not, and you can dream up some statements with or without semicolons (as I showed above) that are problematic.

I'm not going to say it's irrational to use semicolons because it is so ingrained in the culture, but please ignore the irrational fear many attempt to support with a convoluted and inaccurate discussion of ASI or mad hand waving. It's pure dogma, friends.

2
  • 2
    only follow the above advice if: 1) you know the javascript language spec 100% 2) you like to think you do and like to show off this 'fact' to others. 3) you like writing obscure, untraceable bugs for no good reason.
    – Spongman
    Aug 15, 2017 at 23:40
  • 1
    Or if you use TypeScript... which is the whole point of the question, because it will warn you at compile time when a semicolon is missing in a place which might have otherwise lead to "untraceable bugs".
    – DanielM
    Dec 12, 2017 at 8:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.