Why and when to use the semicolon?


"I'm pretty new to all this stuff, but there isn't any difference
if I do use a semicolon or if I don't. Can someone explain this?


In Javascript there is no diffrence. But in other low-level languages like:


Semicolon is mandatory when your ending a statement. semicolon basically tells your langauge thats where the statement ends. Low-level languages are basically the ancecstor lagnuages. the old age, the ones that are used a lot, and you can make many things from them(general purpose programming language)


As the language evolves it is less and less dependent upon the old syntax of ending statements with semi-colons, but we're not there yet. ES6 seems to have really relaxed this syntax rule But here we are still working with ES5.

Part of the reason for using semi-colons is so that the code doesn't break if it is minified (white space removed).

Where there is not indication that a statement is complete the parser will run onto the next statement which when compiled will throw an error (combining two statements in a single parse process is not compilable).


var a = 1
var b = 3
var c = 7

These lines will compile correctly, even without the ; since the white space (newline character, in this case) acts as the delimiter.

var a=1var b=3var c=7

This line will throw an exception, something like, unexpected token or unexpected identifier.

    var a=1;var b=3;var c=7;

Now it will compile, just as the first example since the statements are delimited.

When not to use a ;

After any } UNLESS it is an expression.

var myObject = {};
var myFunction = function () {};

The object on the right side of the equals is an expression.

function foo() {}
while () {}
if () {} else if () {} else {}
for () {}
switch () {}

Pretty much everything else gets a semi-colon.

do {} while ();
var a = parseInt(n,2);