Semicolon - What Is It There For? - Codecademy

The semi-colon, ; indicates an end of statement which is JavaScript’s way of knowing the instruction is spelled out completely.

Some statements have a special characteristic, in that they self close. JavaScript knows they have reached the end. This can be said for if(){}, for(){} and while(){}, function(){}. All of these statements have well defined demarcation.

Anything that ends with ) is not self contained, because it lacks the code blocks (clauses) of the ones shown above. myFunctionCall();, string.toLowerCase();, console.log(args);, and so on. These all require end of statement syntax.

This includes do {} while ();, just in case we were wondering.

We should not just assume, though, that {} is self closing. If it is preceded by an = (assignment operator) then it is not self closing, as it is part of an assignment statement, which always gets an end of statement, as in. var obj = {};.

Bracket notation, var arr = [];, var a = obj[key];.

It follows that anytime we refer to an object, we are making a statement of some sort. These always get, you guessed it, ; at the end.

There should be no characters on the same line following a semi-colon unless they make up another statement that likewise ends with a semi-colon. In other words, we can combine statements on a single line as long as we wish, providing they conform to syntax. Not a practice we will start here, mind you. And for good reason. It is unreadable.

We especially want to avoid placing semi-colons before { as this will break the script.

// code do not's // for (.); {.} // end of statement before code block while (.); {.} // likewise if (.); {.} // also likewise // lastly, do {}; while(); // end of statement before condition

The last one looks like two statements.

To avoid these described snags, it’s a good practice to create our structure before filling in the details.

for () { // } else if { // } else { // }

Similarly,

for () { // }

Or,

function foo() { // }

Lastly,

var bar = function() { // };

Tag » What Does Semicolon Mean In Java