Reputation: 6729
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.
Upvotes: 5
Views: 479
Reputation: 992717
The exact reasons why are probably lost in the mists of time. I'm willing to bet that it happened something like this:
return
statements in the way you describe.Upvotes: 4
Reputation: 4755
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.
Upvotes: 1
Reputation: 887225
This is a "feature", not a bug.
Semicolons in Javascript are optional.
Upvotes: -2