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(); };
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();
Now, invoking this function returns the desired string:
console.log(f("testing")); // "TESTING"
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(); };
Invoking this modified function produces the same result:
console.log(f("testing")); // "TESTING"
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!