Chris Middleton
Chris Middleton

Reputation: 5934

Do parentheses prevent semicolon insertion?

Say that I want to set a bunch of variables equal to null (and don't want to use an array/loop structure) or maybe I just want to write a large boolean expression across multiple lines. Does an unclosed parenthetical prevent semicolon insertion in such a case? E.g.

some_variable = another_variable = yet_another_variable = (
    oh_look_a_parenthesis_above_me = hey_heres_another_variable) = (
    and_for_some_reason_another = last_one) = null;

Or

if(test_for_some_complex_expr && another_test || (
    but_maybe_this_one && or_this_one)) {
    // ...
}

And how does this compare versus using && or || or = to group expressions over line breaks? I.e., would this always work too?

some_variable = another_variable = 
    a_variable_after_a_line_break = and_one_more;

while(test_for_an_expr && another_test || 
    (an_expr_here && and_an_expr_here)) {
    // ...
}

I'm looking for the way that is most standard across all browsers (including IE6+).

Upvotes: 1

Views: 456

Answers (2)

JacquesB
JacquesB

Reputation: 42669

Semicolon insertion only happens if you have code which would be a syntax error without the semicolon. In your case the expression is perfectly valid, so you don't need to worry about semicolon insertion - parentheses or not.

An example where semicolon insertion will happen:

var a = 1
var b = 2

In the above case, a semicolon is inserted at the line break, but only because it is a syntax error to write:

var a = 1 var b = 2

but it is perfectly valid to write:

var a = 1; var b = 2

The rules get tricky because there are some instances in JavaScript syntax where line breaks are NOT allowed. For example a line break is NOT allowed between the 'return' keyword and a value to return. So this is a syntax error:

return
  17;

But the way semicolon insertion "fixes" this error is by inserting a semicolon like this:

return;
  17;

Which is probably not what the writer intended! In that particular case, a parenthesis can be used to prevent semicolon insertion:

return (
   17);

Because it only between the return keyword and the start of the expression that line break is disallowed. Inside an expression it is not a problem.

Upvotes: 2

Bergi
Bergi

Reputation: 664559

Does an unclosed parenthetical prevent semicolon insertion in such a case?

Yes. Although it is unnecessary:

And how does this compare versus using && or || or = to group expressions over line breaks?

It's exactly the same. They are expressions that require a second part, therefore ASI cannot - must not - kick in without making the result invalid.

ASI will only occur when the continued line is invalid without the semicolon. See What are the rules for JavaScript's automatic semicolon insertion (ASI)? for details.

Upvotes: 1

Related Questions