How to Return an Object Literal With JavaScript's Arrow Function?

To return an object literal with the short-hand arrow function syntax (also known as the concise arrow function), you simply need to wrap it in parentheses. For example:

const person = () => ({ name: 'John Doe', age: 24 });

Which is equivalent to:

const person = function() {
    return { name: 'John Doe', age: 24 };
};

To understand why the object literal needs to be wrapped in parentheses, you need to be familiar with the two syntaxes of the arrow function:

  1. Concise Arrow Function: consists of a single expression, result of which implictly becomes the return value of the function.
  2. Fat Arrow Function: consists of a block of statements wrapped in a pair of curly braces that denote a function's body. To make the function return something, an explicit return statement must be added.

Because of the use of curly braces in the fat arrow function syntax, when we try to return an object literal in the concise arrow function syntax (without parentheses), it processes it as a fat arrow function instead. Therefore, to treat the object literal as an expression (as opposed to a block of statements), we need to wrap the object literal in parentheses.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.