When to use semicolon in JavaScript?

Semicolon is required only when you need to separate multiple statements on the same line.

Semicolon is optional, except when you need to separate multiple statements on the same line:

  • In a for loop
  • When declaring multiple variables on the same line
  • When executing multiple statements on the same line

In a for loop

for (let i = 0; i < 10; i++) { // <- here
  if (i === 5) {
    console.log('Hello World!')
  }
}

Declaring multiple variables on the same line

const a = 1; const b = 2; const c = 3 // <- here

console.log(a) // 1
console.log(b) // 2
console.log(c) // 3

Executing multiple statements on the same line

let a = 1

a++; a = a * 5; console.log(a) // <- here (logs 10)