JavaScript: Semicolon Rules

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

ALWAYS add semicolon at end of assignment or statement.

A redundant semicolon is a empty statement. Extra semicolon won't hurt.

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?

Suppose if we can turn off the JavaScript spec's Automatic Semicolon Insertion, then, when do we need a semicolon?

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]

Using Semicolon in Practice

Here is code examples using semicolon.

Variable Assignment

Always use semicolon at end of variable assignment.

const x = 4; // semicolon

const y = {p1:1, p2:2}; // semicolon

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

Function Declaration

For function declarations, no need semicolon.

// function declaration
function f1() {
    // ...
} // semicolon not required here

Last Statement Inside a Function Body

Last statement inside a function body should have a semicolon.

return statement should have a semicolon.

function ff() {
    return 3; // ← semicolon is technically required here
}

No Multi-Line Return Statement

Never have a return statement by itself on a line.

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

// this is bad. JS will add a semicolon at end of return.
// so the function will just return undefined

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

Function Call

A function call, returns a expression.

// function call

(function () {
    return 3;
})(); // better add semicolon here

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