Semi-Colons in JS

In many programming languages like C, C++, and Java, a semicolon (;) is strictly required to terminate a statement. This allows the compiler to know exactly where one instruction ends and the next begins, irrespective of whitespace or line breaks.

For example, this is valid C code:

int x = 5; int y = 10;

Optional Semicolons

In JavaScript, semicolons act as statement terminators as well, but they are technically optional. The JavaScript engine includes a mechanism called Automatic Semicolon Insertion (ASI) that attempts to intelligently insert semicolons during the parsing phase based on line breaks.

Because of ASI, the following code will execute perfectly:

let x = 5
let y = 10

Best Practices

Despite ASI, relying on the engine to insert semicolons can occasionally lead to unexpected parsing errors, especially when statements begin with parentheses or square brackets on new lines.

Most developers—and established style guides—prefer to explicitly write semicolons to avoid any ambiguity.

// Preferred styling
let x = 5;
let y = 10;

Practical Example

If you need to compress code or run multiple commands on a single line (perhaps within a build script), semicolons become mandatory. Without them, the engine cannot separate the logic.

// This works because the semicolon acts as a hard break between the commands
console.log("contacting cell tower..."); console.log("sending message...");