Home  >  Article  >  Web Front-end  >  Why Does a Newline After `return` in JavaScript Cause `undefined` to Be Returned?

Why Does a Newline After `return` in JavaScript Cause `undefined` to Be Returned?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-06 11:20:03837browse

Why Does a Newline After `return` in JavaScript Cause `undefined` to Be Returned?

Javascript: Why Return Statement on a New Line Doesn't Work?

In JavaScript, the return statement is used to return a value from a function. However, unexpected behavior can occur when the return value is placed on a new line. Let's delve into why this happens.

To illustrate the issue, consider the following code:

<code class="javascript">function correct() {
  return 15;
}

function wrong() {
  return
        15;
}</code>

In the correct() function, the return 15 statement is on a single line. Running this function will return the expected value, 15. However, the wrong() function has the return statement followed by a new line. Executing this function returns undefined instead of 15.

Surprisingly, the following wrong() implementation works correctly:

<code class="javascript">function wrong() {
  return(
        15);
}</code>

This suggests that the syntax is not incorrect, so why does the first wrong() implementation fail?

Understanding the Role of Semicolons

In JavaScript, semicolons are optional. However, the interpreter automatically inserts them at certain newline characters where it deems them necessary. In the case of the first wrong() implementation, the newline after return triggers the insertion of a semicolon.

The resulting code looks like this:

<code class="javascript">function wrong() {
  return;
        15;
}</code>

This is incorrect, as the return statement is now followed by an expression (15), which is not allowed.

Parenthesis to the Rescue

In the second wrong() implementation, the parentheses () enclosing the return 15 expression prevent the interpreter from inserting a semicolon. Instead, the expression remains intact, resulting in the correct return value.

Therefore, in JavaScript, when using the return statement, ensure that it is on a single line without any subsequent expressions. If necessary, use parentheses to control semicolon insertion behavior and achieve the desired return value.

The above is the detailed content of Why Does a Newline After `return` in JavaScript Cause `undefined` to Be Returned?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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