Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are semicolons mandatory in javascript statements? [duplicate]

Tags:

javascript

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).

like image 348
Kanishka Panamaldeniya Avatar asked Nov 13 '11 01:11

Kanishka Panamaldeniya


1 Answers

Semicolons are not always mandatory, but I would always recommend using them. See the ECMAScript spec for the rules on automatic semicolon insertion:

Certain ECMAScript statements (empty statement, variable statement, expression statement, do-while statement, continue statement, break statement, return statement, and throw statement) must be terminated with semicolons. Such semicolons may always appear explicitly in the source text. For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.

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:

function something(a, b) {
    return
    a + b;
}

What you may be expecting is for the new-line to be ignored, and the code interpreted as:

function something(a, b) {
    return a + b;
}

Unfortunately, automatic semicolon insertion comes into play, and the code is actually interpreted like this:

function something(a, b) {
    return;
    a + b;
}

And an empty return statement means the function returns undefined. So instead of a nice sum of the two argument, you get undefined and 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.

  • Example (returns undefined because of ASI).
  • Example (returns expected result).
like image 73
James Allardice Avatar answered Oct 07 '22 16:10

James Allardice