Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is JavaScript designed to automatically insert a semicolon after a return followed by a new line?

I just ran into a problem where I did:

return
    isSomething() &&
    isSomethingElse();

Which doesn't work because JavaScript inserts the semicolon after the return making the above equivalent to:

return;
isSomething() && isSomethingElse();

This totally baffled me as to why it does this. I found some Stack Overflow questions about the topic (e.g. this, this, and this) but they just explain when it does this, referring to the specs.

I can't even imagine a situation where I would want to have a return; statement followed by some other valid JavaScript statements (unless you use goto or maybe some other obscure JavaScript I haven't heard of). In my opinion, this can only cause problems.

What I'm wondering is why it does this. Why is this part of the spec?

Concerning the close as duplicate. I think I clearly stated that I read other questions and answers stating that it's part of the JavaScript spec and even put the part that distinguishes my question from the others in bold. The question that is linked in the close reason does not contain an answer to this question and is of the exact same form as the other three questions I linked as not answering my question.

like image 556
Matthijs Wessels Avatar asked Oct 20 '22 08:10

Matthijs Wessels


1 Answers

The exact reasons why are probably lost in the mists of time. I'm willing to bet that it happened something like this:

  • At some point, somebody thought it would be a good idea to make semicolons optional at the end of statements.
  • Later on, somebody else noticed an ambiguity in the syntax when semicolons were omitted when used with return statements in the way you describe.
  • The formal language specification was then amended with the confusing new rule about omitted semicolons on return statements, to codify current practice rather than changing the rules to make sense.
like image 159
Greg Hewgill Avatar answered Oct 23 '22 01:10

Greg Hewgill