Why Object Literal Returns Need Parentheses in Arrow Functions: An Explainer

Why Object Literal Returns Need Parentheses in Arrow Functions: An Explainer

The reason why an object literal must be wrapped in parentheses when returned from an arrow function, but not from a traditional function, is related to the rules for Automatic Semicolon Insertion (ASI) in JavaScript.

Read more about πŸ‘‰πŸΌAutomatic Semicolon Insertion (ASI)πŸ‘ˆπŸΌ

In JavaScript, semicolons are automatically inserted at certain points in the code, and the rules for when semicolons are inserted can sometimes lead to unexpected behavior. To avoid this, it is a common practice to wrap object literals in parentheses to indicate that they are expressions and to prevent any confusion or issues that could arise from the ASI rules.

When using a traditional function, the code inside the function is wrapped in a block, which allows for the object literal to be returned without the need for parentheses.

However, when using an arrow function, the rules for ASI are more strict, and omitting the parentheses can result in a syntax error. Therefore, it is necessary to wrap the object literal in parentheses when returning it from an arrow function.

Here is an example of a traditional function that returns an object literal:

function traditionalFunction() {
  return {
    key: 'value'
  };
}

And here is an example of an arrow function that returns an object literal:

const arrowFunction = () => ({
  key: 'value'
});

In both cases, the object literal is returned successfully, but the syntax is slightly different due to the differences in the rules for ASI between traditional functions and arrow functions.

Follow me on Twitter for more such blogs.

Cheers 🍻

Did you find this article valuable?

Support Gautam Balamurali by becoming a sponsor. Any amount is appreciated!

Β