typescriptcoding-style

When is it appropriate to use a semicolon?


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.


Solution

  • 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 should prefix the second line with a semicolon:

    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