Javascript is required
Mokkapps LogoMichael Hoffmann

JavaScript Tip: Return Object Literal From an Arrow Function

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
Michael Hoffmann
Jan 23, 2023
1 min read
JavaScript Tip: Return Object Literal From an Arrow Function Image

ECMAScript 2015 introduced the use of arrow functions, which offer a concise syntax for defining functions without the need for the function keyword.

An example of this shorthand syntax can be seen in a function that doubles a given integer:

const doubleCount = (value) => {  return {    doubleCount: value * 2,  }}

You might be tempted to simplify the code by removing the return statement, like this:

const doubleCount = (value) => {  doubleCount: value * 2}

Upon calling the doubleCount function, it is observed that it is not functioning as intended. Regardless of the input value passed, the function returns undefined. Why is that?

The problem with the arrow function is that it's not returning the expected value because the parser is treating the braces as a block statement instead of an object literal. As a result, the parser is interpreting the label doubleCount as belonging to the expression statement value * 2 and there is no return statement, resulting in the function returning undefined.

To correct this behavior, you must ensure that the parser interprets the object literal as an expression instead of a block statement. This can be achieved by adding parentheses around the entire body of the function:

const doubleCount = (value) => ({  doubleCount: value * 2,})

If you liked this tip, follow me on Twitter to get notified about new tips, blog posts, and more.