In languages like C, C++, and Java, a semicolon is used as a statement terminator. For example, in C:
int x = 5;
This allows the compiler to know when a statement ends without relying on whitespace or newlines. For example, this is also valid C:
int x = 5; int y = 10;
In JavaScript, semicolons are optional as a terminating character. They can be inserted by the JavaScript engine automatically during the parsing phase. However, most developers (us included) prefer to use semi-colons to avoid any confusion or errors that can arise from automatic insertion.
// This works
let x = 5
let y = 10
// But we prefer this
let x = 5;
let y = 10;
Just so we can understand what semicolons allow for, let's fix a bug in the provided 2-statement program on a single line.
Run the code and notice that there is an error given. Fix the error on a single line by adding a semicolon as a separating character.