When working with arrow functions in JavaScript, there are two common ways to return values: implicit return and explicit return. Let’s dive into each one!
1. Implicit Return
In JavaScript, arrow functions can automatically return values without needing the return keyword. This is called implicit return. It works when the function contains a single expression, and the result of that expression is automatically returned.
Example:
const add = (a, b) => a + b;
console.log(add(2, 3)); // Output: 5
// or
const setData = (prevData) => ({
...prevData,
content: 'lorem ipsum'
});
Notice that there’s no return keyword in the body of the function. The result of a + b is implicitly returned.
2. Explicit Return
Sometimes, you might need to execute multiple operations within a function or the function has a block body (using {}). In these cases, you must use the return keyword to explicitly return a value.
Example:
const setData = (prevData) => {
return {
...prevData,
content: 'lorem ipsum'
};
};
Here, the return keyword is necessary because the function body is enclosed in {}, and we need to explicitly return the updated object.
Conclusion
- Implicit return: Ideal for concise, single-expression functions.
- Explicit return: Required for functions with multiple statements or a block body.
Both approaches have their uses, and understanding when to use each can help you write cleaner, more readable code!
Top comments (2)
Good breakdown. One gotcha I'd add — the parentheses around the object literal in the implicit return example
({ ...prevData })trips up so many people. Without them JS thinks the curly braces are a block statement, not an object. I've seen this bug in code reviews more times than I can count. Also worth noting that if you need to add a console.log for debugging, you suddenly have to convert to explicit return. Some people use the comma operator trick=> (console.log(x), x)but honestly I think just switching to explicit is cleaner and more readable at that point.Hello Kai, thank you so much for these two great additions!
For the first point; yes, this is a really common gotcha. I'd actually love to expand on it a bit: the parentheses are needed because without them, JS sees the
{and thinks you're opening a block statement, not creating an object. So wrapping it in()is basically telling JS: "hey, this is an expression (an object), not a code block."And didn't know about the comma operator trick, also agree that switching to explicit return is much cleaner and easier to read when you need to add a console.log or any extra logic.
Really appreciate you adding these, they make the post more complete!