Is this the expected behavior with the return keyword in JavaScript?
I was on the verge of pulling all my hair out today by a stupid mistake. The point is, I'm not sure if this is the expected behavior.
With my C # habits, I wrote the following javascript code and tried to figure out what was going wrong because it didn't return anything and didn't even log any errors to the console:
this.fullName = ko.computed(function () {
return
this.firstName() + " " + this.lastName();
}, this);
Then (half an hour later) I changed the code a below and it worked:
this.fullName = ko.computed(function () {
return this.firstName() + " " + this.lastName();
}, this);
Is this the expected behavior?
source to share
Yes. This is an implicit semicolon.
Here's a similar situation with clarifications: http://premii.com/lab/js_implicit_semicolon_and_return.php
In short: your first snippet is interpreted as:
this.fullName = ko.computed(function () {
return;
this.firstName() + " " + this.lastName();
}, this);
source to share
Yes The ECMA specification , which is a Javascript specification, defines behavior like this
Certain ECMAScript statements (empty statement, ... return statement and throw statement) must be terminated with a semicolon. Such semicolons can 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 that semicolons are automatically inserted into the source token stream in these situations.
Further
When a continue, break, return, or throw marker is encountered and LineTerminator is encountered before the next token, a semicolon is automatically inserted after a continuation, break, return, or token throw.
The return expression or throw statement must begin on the same line as the return or throw token.
And they gave an example of:
Source
return
a + b
is converted by automatic semicolon insertion into the following:
return;
a + b;
So your first code will be interpreted as:
return;
this.firstName() + " " + this.lastName();
with an automatically added semitone at the end of the return.
Thus, the spec provides practical advice to counter these situations in general javascript:
The postfix ++ or - operator must appear on the same line as its operand.
The expression in a return or throw statement must begin with the same as a return or throw marker.
The identifier in a break or continue statement must be on the same as a break or continuation token.
source to share