3) Learn to Crawl Before You Can Run Lesson

JavaScript Syntax: Semicolons

3 min to complete · By Ian Currie

In Javascript, there are only a few situations in which semicolons are necessary.

It is considered good practice to use semicolons at the end of expressions, but the JavaScript language has Automatic Semicolon Insertion (ASI) rules to determine when a semicolon is needed. These rules are inherited from C, which requires semicolons at the end of expressions.

An Example of When to Use Semicolons

In this course, you may see that sometimes the semicolon is omitted, especially when demonstrating different ways to write the same thing. You will see it everywhere out in the wild world of the web though. Just bear in mind that there are some cases in which the semi-colon is necessary.

One notable example where the semicolon is necessary is the for loop. Have a look at this example:

for (let i = 0; i < 10; i++) {
  console.log(i);
}

Different Uses of Semicolons

Semicolons serve different purposes.

The code above displays two use cases:

  1. On line 1, there are effectively 3 statements within the brackets, and these require a semicolon to separate them.
  2. On line two, however, the semicolon that indicates the end of that statement, is not necessary, but is good practice to include.

Useful Tools

There are plugins for VSCode like Prettier that will format your code for you. They have an online playground in which you can paste code to be formatted.

This will be great for you to use when you complete your labs so you can see how to format your code as a professional would.

Summary: When to Use the Javascript Semicolon

  • Semicolons are necessary only in a few situations
  • The for loop is an example of a situation where the semicolon is required
  • It is good practice to use them at the end of expressions
  • Prettier is a useful VSCode plugin that helps format your code for you