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

Why Do Some Arrow Functions Return `undefined` in JavaScript?

Patricia Arquette
Release: 2024-12-18 05:25:09
Original
318 people have browsed it

Why Do Some Arrow Functions Return `undefined` in JavaScript?

Why Arrow Functions May Return Undefined: The Explicit Return vs. Implicit Return Conundrum

Arrow functions offer a concise syntax for defining functions in JavaScript. However, when dealing with function bodies wrapped in parentheses ({}), beginners often encounter a peculiar issue: why do these arrow functions return undefined?

Consider the following simplified example:

const f = arg => { arg.toUpperCase(); };
console.log(f("testing")); // undefined
Copy after login

This arrow function is meant to convert the argument to uppercase, but it returns undefined. The reason lies in the optional curly braces around the body of the arrow function.

Unlike arrow functions with concise bodies (without curly braces), where the body expression is implicitly returned, arrow functions with function body syntax require an explicit return statement. In the original example, the absence of an explicit return results in undefined being returned instead of the uppercase argument.

To rectify this, you can either use an explicit return:

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

Or use a concise body:

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

Examples with explicit return and concise body:

const f1 = arg => { return arg.toUpperCase(); };
console.log(f1("testing"));

const f2 = arg => arg.toUpperCase();
console.log(f2("testing"));
Copy after login

By adhering to these rules, you can ensure that your arrow functions always return the intended value, whether it be through explicit or implicit returns.

The above is the detailed content of Why Do Some Arrow Functions Return `undefined` in JavaScript?. 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