Home > Web Front-end > JS Tutorial > body text

Why Does JavaScript's `return` Statement Sometimes Return `undefined`?

DDD
Release: 2024-11-05 16:14:02
Original
258 people have browsed it

Why Does JavaScript's `return` Statement Sometimes Return `undefined`?

JavaScript's Mysterious Return Statement Conundrum

Consider the following JavaScript code snippet:

function correct() {
  return 15;
}

function wrong() {
  return 15;
}

console.log("correct() called : " + correct());
console.log("wrong() called : " + wrong());
Copy after login

Surprisingly, correct() returns the expected value of 15, while wrong() returns undefined. This behavior differs from most other programming languages, leaving us wondering why it occurs.

The Technical Explanation: Invisible Semicolons

JavaScript's semi-colons are optional, and the interpreter automatically inserts them at certain newline characters. However, the interpreter's assumptions may not always align with our intentions.

In the case of wrong(), the return statement is followed by a newline. This triggers the insertion of a semicolon, resulting in the following code:

function wrong() {
  return;
  15;
}
Copy after login

Breaking down the Issue: Return Syntax

The return statement must be immediately followed by the return value. In wrong(), the semicolon after return terminates the statement, leaving the following line disconnected.

The Solution: Enclosing Expressions in Parentheses

To avoid this confusion, we can enclose the return expression in parentheses:

function wrong() {
  return (
    15
  );
}
Copy after login

The parentheses prevent the interpreter from inserting a semicolon and ensure that the expression is correctly evaluated.

Understanding TypeScript's Reasoning

TypeScript, JavaScript's typed superset, issues a compiler error in the above code, highlighting the importance of correct return statement syntax. This emphasizes the criticality of such considerations when defining functions in JavaScript.

The above is the detailed content of Why Does JavaScript's `return` Statement Sometimes Return `undefined`?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!