Why Javascript's Return Statement Fails with Return Value on a New Line
Consider the JavaScript code below:
<code class="javascript">function correct() { return 15; } function wrong() { return 15; } console.log("correct() called : "+correct()); console.log("wrong() called : "+wrong());</code>
In this example, correct() correctly returns 15, while wrong() inexplicably returns undefined. This behavior is distinct from other programming languages. The following alternative implementation of wrong() rectifies the issue:
<code class="javascript">function wrong() { return( 15); }</code>
Why does this happen?
JS interpreters optionally insert semicolons at certain newlines when they deem them necessary. However, their judgement can differ from what is intended.
When a return statement is followed by a newline, the JS interpreter inserts a semicolon after the return statement. This results in the wrong() function's code being modified to:
<code class="javascript">function wrong() { return; 15; }</code>
This is now incorrect.
In contrast, the modified version of wrong() with the added parentheses starts an expression with an open parenthesis. The JS interpreter recognizes this and refrains from inserting a semicolon, preserving the intended behavior.
The above is the detailed content of Why Does JavaScript's `return` Statement Fail with a Return Value on a New Line?. For more information, please follow other related articles on the PHP Chinese website!