·
1 min read

JavaScript Tip: Return Object Literal From an Arrow Function

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:

1const doubleCount = (value) => {
2  return {
3    doubleCount: value * 2,
4  }
5}

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

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

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:

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