Home >Web Front-end >JS Tutorial >When Do ES6 Arrow Functions Require an Explicit `return` Statement?
When is an Explicit Return Required in ES6 Arrow Functions?
In ES6, arrow functions implicitly return the expression within their concise body, eliminating the need for the return keyword in scenarios with a single expression. However, there are specific cases where an explicit return statement is still necessary.
When to Use return with Arrow Functions
() => { console.log('Hello'); } // Implicit return, logs 'Hello' () => { return 'Hello'; } // Explicit return, returns 'Hello'
(name) => {id: name}
Returns undefined because the braces indicate a block, interpreting id as a label rather than a property name.
Examples
Implicit Return:
(name) => name + '!'; // Implicit return, returns 'Jess!'
Explicit Return:
(name) => { return name + '!'; } // Explicit return, returns 'Jess!'
In summary, if an arrow function contains a block, has ambiguous syntax, or spans multiple lines, an explicit return statement is necessary to specify the function's return value. Otherwise, the expression in the arrow function's body is implicitly returned.
The above is the detailed content of When Do ES6 Arrow Functions Require an Explicit `return` Statement?. For more information, please follow other related articles on the PHP Chinese website!