January 26, 2023

The semicolon in JavaScript / TypeScript: pros and cons

The need to use semicolons in JavaScript and similar languages ​​is a hotly debated topic. In this article, I will try to break down all the pros and cons of using a semicolon.

ASI (Automatic Semicolon Insertion)

The use of semicolons in JavaScript is optional due to the existence of ASI. TypeScript also uses ASI. However, ASI does not always function correctly, and there are several situations where missing a semicolon will lead to an unexpected runtime error.

JavaScript has several dead ends that are fixed by the TypeScript type system. For example:


class Car {

  color;

  constructor(color) {
  
    this.color = color;
    
  }

  beep() {
  
    console.log("BEEEEP");
    
  }
  
}
console.log("test") //; It won't work without a semicolon

[("white", "blue")].forEach((color) => new Car(color).beep());

The array of colors will be interpreted as a semicolon expression. In JS, this will throw a runtime error - "Uncaught TypeError: Cannot read property 'blue' of undefined" ". In TS, an error will occur at the compilation stage - "Left side of comma operator is unused and has no side effects".

There is another similar example. In this case, the error will occur in both languages ​​only at runtime:


console.log("n");

(function() {

    console.log("n");
    
}())

If you are using a linter, the no-unexpected-multiline flag will help you catch these errors at compile time.

Reasons to use semicolons:

Reasons not to use semicolons:

Keep reading😊

Text Link
marketing
SEO
February 7, 2023

7 Proven Strategies for Finding Clients for Your Business

Read more
coding tips
Web development
back-end
front-end
Mobile design
January 26, 2023

The semicolon in JavaScript / TypeScript: pros and cons

Read more