JavaScript Tip: Returning Objects with Arrow Functions
When writing modern JavaScript, arrow functions are a go-to syntax for many developers. But there’s a small detail that trips up even experienced coders: how to return an object from an arrow function.
Let me show you two ways to return the same object:
Example 1: Explicit return
with Curly Braces
const returnObject = () => { return { name: 'Gihan' }; };
Here, the function uses curly braces {}
to define a block body, and the return
keyword is required to return the object.
Example 2: Implicit Return with Parentheses
const returnObject = () => ({ name: 'Gihan' });
This version is shorter and uses implicit return. The parentheses ()
are critical — they tell JavaScript you’re returning an object, not creating a block.
⚠️ Gotcha: This Won’t Work
const returnObject = () => { name: 'Gihan'; };
Looks harmless? This returns undefined
because JavaScript sees {}
as a function block, not an object. There’s no return statement, so nothing is returned.
💡 When to Use Which?
-
Use the explicit
return
+ block when:-
You need to perform logic before returning
-
You’re returning conditionally
-
-
Use implicit return with
()
for:-
Short, clean functions
-
Returning simple objects
-
Final Thoughts
This is a small but important detail in writing clean and bug-free JavaScript. Mastering these nuances helps you avoid hidden issues and write more expressive code — something recruiters and teams truly value.