JavaScript: Semicolon Rules
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:
- A line should never start with left parenthesis () nor left square bracket [].
- If a line starts with parenthesis or square bracket, add a semicolon in the beginning of line (or end of previous line).
Advantage of Omitting Semicolon
- Less typing.
Disadvantage of Omitting Semicolon
- Code becomes layout dependent. If you join 2 lines into 1 line, the code won't run correctly.
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?
let x = value;
(Assignment needs semicolon)(function name (param) {body}(arg));
(immediately invoked function expression.)
- No need semicolon at end of declaration
function name (param) {body}
. - No need semicolon at end of
for
statement. - No need semicolon at end of
while
statement. - No need semicolon at end of
if
statement. - No need semicolon at end of
switch
statement. - No need semicolon at end of
try
statement.
The full spec is fairly complex.
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 })(); ^ */