Home > Web Front-end > JS Tutorial > Why Does JavaScript's `return` Statement Fail with a Return Value on a New Line?

Why Does JavaScript's `return` Statement Fail with a Return Value on a New Line?

Mary-Kate Olsen
Release: 2024-11-08 04:20:02
Original
534 people have browsed it

Why Does JavaScript's `return` Statement Fail with a Return Value on a New Line?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template