DEV Community

Cover image for The semicolon in JavaScript / TypeScript: pros and cons

The semicolon in JavaScript / TypeScript: pros and cons

b3ns44d profile image Abdessamad Bensaad ・2 min read

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 {

  constructor(color) {
    this.color = color;

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

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

Enter fullscreen mode Exit fullscreen mode

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:

(function() {
Enter fullscreen mode Exit fullscreen mode

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

Reasons to use semicolons

  • Habit - why change something, if everything suits you.
  • Different programming languages ​​- It's easier to stick to similar principles in different languages.
  • Readability is a matter of taste.
  • Getting rid of ambiguities.
  • Reluctance to use the linter.

Reasons not to use semicolons

  • An extra symbol - saving time and space.
  • The code becomes cleaner.
  • It's easier to hit the end of the line with the mouse.
  • Linter - allows you to detect errors at the compilation stage.
  • It's easier for beginners not to be distracted by semicolons.
  • No more warnings about missing semicolons (especially when moving from a language that doesn't use them).
  • Using semicolons in JavaScript and TypeScript does not completely eliminate ambiguities.

Discussion (0)

Forem Open with the Forem app