Home >Web Front-end >JS Tutorial >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
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 ^^^^^^
Or use a concise body:
const f = arg => arg.toUpperCase();
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"));
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!