Course contentsShow
← JavaScript
Lesson 401 of 2,72311. FunctionsFree lesson

Returning Object Literals from Arrow Functions

Master the syntax for returning object literals by wrapping them in parentheses to avoid ambiguity.

Returning Object Literals from Arrow Functions

You'll learn how to return an object directly from an arrow function without JavaScript mistaking it for a code block.

The Ambiguity Problem

When you write a single-expression arrow function, JavaScript normally returns the result automatically. But there's a catch: curly braces {} are used both for object literals and for marking code blocks. If you try to return an object literal, JavaScript sees the braces and thinks you're starting a function body, not creating an object!

// This DOESN'T work as expected
const getUser = () => { name: "Alice", age: 25 };
// JavaScript thinks { } is a block, not an object
// Returns undefined!

The Solution: Wrap in Parentheses

To tell JavaScript "this is an object, not a block," wrap the object literal in parentheses:

// This WORKS correctly
const getUser = () => ({ name: "Alice", age: 25 });

const user = getUser();
console.log(user.name); // "Alice"

The parentheses force JavaScript to interpret the braces as an object literal. Think of the parentheses as saying, "Treat everything inside as a single expression."

Common Use Case

This pattern shines when working with array methods:

const ids = [1, 2, 3];
const users = ids.map(id => ({ id: id, active: true }));

console.log(users);
// [{ id: 1, active: true }, { id: 2, active: true }, { id: 3, active: true }]

Key Takeaway: When returning an object literal from a single-expression arrow function, wrap it in parentheses ({ ... }) to avoid JavaScript interpreting the braces as a function block.