I want to know, is this legal?
function test()
{
alert ("hello")
$("#loading").show();
}
Or should I write this instead:
function test()
{
alert ("hello");
$("#loading").show();
}
Are semicolons optional in JavaScript? Because I saw this in a forum:
No, semicolons are usually optional in JavaScript (Google for ASI / automatic semicolon insertion). Using them makes the code look much cleaner though and ASI is a horrible mis-feature (at least in my opinion).
Semicolons are not always mandatory, but I would always recommend using them. See the ECMAScript spec for the rules on automatic semicolon insertion:
Update (to explain further)
Perhaps the most common situation used to show why automatic semicolon insertion can be bad is that touched on by @sissonb in another answer. Consider the following:
What you may be expecting is for the new-line to be ignored, and the code interpreted as:
Unfortunately, automatic semicolon insertion comes into play, and the code is actually interpreted like this:
And an empty
returnstatement means the function returnsundefined. So instead of a nice sum of the two argument, you getundefinedand potentially end up very confused as to where you’ve gone wrong! Which is why I completely agree with the statement in your question that automatic semicolon insertion is a horrible misfeature.undefinedbecause of ASI).