Home > Web Front-end > JS Tutorial > Why Do Some JavaScript Arrow Functions Return `undefined`?

Why Do Some JavaScript Arrow Functions Return `undefined`?

Patricia Arquette
Release: 2024-12-20 08:36:10
Original
378 people have browsed it

Why Do Some JavaScript Arrow Functions Return `undefined`?

Arrow Functions and Explicit Return Statements

In JavaScript, arrow functions provide a concise syntax for defining functions. However, a common pitfall is encountering undefined values when calling arrow functions that utilize block bodies.

Consider the following arrow function:

const f = arg => { arg.toUpperCase(); };
Copy after login

While this function may appear logical, it returns undefined when called. To understand why, we need to examine the semantics of arrow functions.

When using the block body (with curly braces) in an arrow function, the implicit return behavior differs from the concise body (without curly braces). In the block body version, the value returned by the function must be explicitly specified using the return keyword.

const f = arg => { return arg.toUpperCase(); };
Copy after login

With this explicit return statement, the function correctly returns the expected value: "TESTING".

Alternatively, you can use the concise body syntax to achieve the same result implicitly:

const f = arg => arg.toUpperCase();
Copy after login

In this case, the last expression in the body, arg.toUpperCase(), is automatically returned by the arrow function.

Therefore, to avoid undefined values when calling arrow functions with block bodies, always explicitly specify the return value using the return keyword or use the concise body syntax.

The above is the detailed content of Why Do Some JavaScript Arrow Functions 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template