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(); };
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(); };
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();
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!