JS: Semicolon

By Xah Lee. Date: . Last updated: .

JavaScript syntax is very complex, such that semicolon can sometimes be omitted, sometimes not, and there is no simple rule for programer to remember when it can be omitted.

Rule for Always Using Semicolon Style

need semicolon:

no need semicolon:

Rule for Omitting Semicolon Style

Do not add semicolon, except:

Advantage of Omitting Semicolon

Disadvantage of Omitting Semicolon

Use Automatic Formatting Tool

Use Deno to autoformat code.

deno adds semicolon automatically.

When Do You Need Semicolon by JavaScript Grammar?

The full spec is fairly complex.

js semicolon rule 2022-07-29 jVk5N
js spec on semicolon, 2022-07-29. [https://tc39.es/ecma262/2022/multipage/ecmascript-language-lexical-grammar.html#sec-automatic-semicolon-insertion]

Tips on Semicolon

Return Statement Must be in One-Line

function ff() {
  // bad
  [3, 4, 5];

console.log(ff() === undefined);

Example of Bad Omitted Semicolon

example of erro due to semicolon omission.

you intended to assign the first function, and eval the second.
but js compiler tried to feed the second function as arg to your first function

const f = function () {
  return 3;
} // bad semicolon omission
(function () {
  return 4;


error: Uncaught TypeError: (intermediate value)(...) is not a function

BUY Ξ£JS JavaScript in Depth