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

StackOverflow https://stackoverflow.com/questions/23644421

  •  22-07-2023
  •  | 
  •  

Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

Javascript has this "clever" feature which makes it so that the semicolon is generally optional in your code. If you leave the semicolons off the end of the line, it will add them to the line endings. As per the codeacademy article on the subject:

The semicolon is only obligatory when you have two or more statements on the same line:

var i = 0; i++        // <-- semicolon obligatory
                      //     (but optional before newline)
var i = 0             // <-- semicolon optional
    i++               // <-- semicolon optional

So basically, you can't break your code across multiple lines like that, because Javascript thinks it's smart enough decide you forgot the semicolons and insert them for you.

This is a "feature", not a bug.

Semicolons in Javascript are optional.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top