JavaScript Return Statement on New Line: Why It Fails
Consider the following JavaScript code:
<code class="javascript">function correct() { return 15; } function wrong() { return 15; }</code>
The correct() function returns the expected value of 15, while the wrong() function unexpectedly returns undefined. This behavior differs from other programming languages.
When the return statement is on a new line, JavaScript inserts a semicolon at the end of the preceding line. This is because semicolons are optional in JavaScript, but the interpreter inserts them to maintain code clarity.
In the wrong() function, JavaScript inserts a semicolon after the return, which effectively terminates the function and ignores the following line. Hence, it returns undefined.
To avoid this issue, you can either use parentheses around the return value or avoid placing it on a new line. For example:
<code class="javascript">function wrong() { return( 15); }</code>
By starting an expression with parentheses, JavaScript knows to skip inserting a semicolon at the newline. This ensures that the return value is properly returned.
The above is the detailed content of Why Does Putting a `return` Statement on a New Line in JavaScript Lead to `undefined`?. For more information, please follow other related articles on the PHP Chinese website!