Home >Web Front-end >JS Tutorial >Why Do Some Arrow Functions Return `undefined` While Others Don't?
Understanding Return Values in Arrow Functions: A Dilemma of Explicit vs. Implicit
Arrow functions, introduced in ES6, have gained popularity for their concise syntax and flexibility. However, a common pitfall that plagues novice programmers arises when dealing with their return values.
Consider the following arrow function:
const f = arg => { arg.toUpperCase(); };
When invoked, this function unexpectedly returns undefined. Why is this happening?
The Implicit Return in Concise Arrow Functions
Arrow functions offer two distinct syntax variants: a concise form without curly braces and a more verbose form with curly braces. The concise form implicitly returns the result of the body expression, eliminating the need for an explicit return statement. Thus, an arrow function like arg => arg.toUpperCase(); automatically returns the capitalized argument.
Explicit Returns in Curly-Braced Arrow Functions
On the other hand, arrow functions with curly braces use a traditional function body. In this scenario, there is no implicit return. To obtain a value from such an arrow function, an explicit return statement must be used. Modifying our previous example:
const f = arg => { return arg.toUpperCase(); };
Now, the function will correctly return the capitalized argument. Alternatively, we could use the more concise form by omitting the curly braces:
const f = arg => arg.toUpperCase();
In this case, the arrow function implicitly returns the result of the expression, which is the capitalized argument.
By understanding the difference between implicit and explicit returns in arrow functions, you can avoid the pitfalls that arise when dealing with their return values.
The above is the detailed content of Why Do Some Arrow Functions Return `undefined` While Others Don't?. For more information, please follow other related articles on the PHP Chinese website!