Home > Web Front-end > JS Tutorial > Why Do Arrow Functions with Curly Braces Return `undefined` Unless Explicitly Returned?

Why Do Arrow Functions with Curly Braces Return `undefined` Unless Explicitly Returned?

Susan Sarandon
Release: 2024-12-20 09:33:10
Original
860 people have browsed it

Why Do Arrow Functions with Curly Braces Return `undefined` Unless Explicitly Returned?

Arrow Functions: Understanding the Missing Return Value

In the realm of JavaScript, arrow functions have emerged as a popular choice for concise and expressive code. However, a common pitfall can arise when using the function body version (with curly braces).

The Issue: Missing Return Value

Consider the following arrow function:

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

When invoked, this function returns undefined instead of the expected value. Why is that?

Unveiling the Implied Return

In arrow functions, the return statement is implicitly applied when using the concise body (without curly braces). This means the result of the expression within the parentheses becomes the returned value.

Concise Body Example:

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

Now, invoking this function returns the desired string:

console.log(f("testing")); // "TESTING"
Copy after login
Copy after login

Explicit Return for Function Body

However, when using curly braces, an explicit return statement is necessary to indicate what should be returned. Otherwise, the function will return undefined.

Explicit Return Example:

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

Invoking this modified function produces the same result:

console.log(f("testing")); // "TESTING"
Copy after login
Copy after login

Remember: Implied return exists in the concise body of arrow functions, while explicit return is required when using curly braces for the function body. Understanding this distinction is crucial to avoid unexpected undefined values in your code.

The above is the detailed content of Why Do Arrow Functions with Curly Braces Return `undefined` Unless Explicitly Returned?. 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