Is This An Expected Behavior With Return Keyword On Javascript
Solution 1:
Yes. It's the implicit semicolon.
Here's similar situation with explanations: 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);
Solution 2:
Yes ECMA Spec, which is the Javascript spec, defines the behavior like this
Certain ECMAScript statements (empty statement, ... return statement, and throw statement) must be terminated with semicolons. Such semicolons may 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 by saying that semicolons are automatically inserted into the source code token stream in those situations.
Further more
When a continue, break, return, or throw token is encountered and a LineTerminator is encountered before the next token, a semicolon is automatically inserted after the continue, break, return, or throw token.
An Expression in a return or throw statement should start on the same line as the return or throw token.
And they have given an example of:
The source
return
a + b
is transformed by automatic semicolon insertion into the following:
return;
a + b;
So your first code will be interpreted as:
return;
this.firstName() + " " + this.lastName();
with the automatically added semi colon at the end of return.
So the spec gives practical advice to face these situations in general javascript:
A postfix ++ or -- operator should appear on the same line as its operand.
An Expression in a return or throw statement should start on the same line as the return or throw token.
A Identifier in a break or continue statement should be on the same line as the break or continue token.
Solution 3:
Yes, it is. Javascript doesn't need a semicolon at the end of the line to end the statement. In this case, it simply returns.
Solution 4:
Yes it is, Semicolons in javascript tend to be optional, So there is no exact way to differentiate the complete statement only using semicolons. Check out this book which I hear is a great resource for JS , The good parts of javascript by douglas crockford.
Solution 5:
Javascript has a feather which is Automatic semicolon insertion, which is not good, you should not depend on it and add semicolon when a statement finishes.
In you case, javascript add ;
to the return
statement. so it is same as:
return;
this.firstName() + " " + this.lastName();
Post a Comment for "Is This An Expected Behavior With Return Keyword On Javascript"