Implicit return gotcha for arrow functions

Beware of using implicit returns in arrow functions.

Consider the below example of a simple arrow function. It returns a simple variable. In the absence of any other statement in the function body, a simple mention of x will return the value of x.

const getStuff = x => x;
console.log(getStuff(1));
// 1

Let’s modify the block. We now want to return an object with the input value within it.

const getMoreStuff = x => {
  x: x;
};
console.log(getStuff(1));
// 1

Oops.. We expected {x: 1} but got 1 because the flower brackets were treated as enclosing a function body and not an object.

To get an object, we have to do a simple change -

const getBetterStuff = x => ({ x: x });
console.log(getBetterStuff(1));
// { x: 1 }

We have used double brackets to signify that the return variable is an object (and to indicate that the flower bracket is not meant to start a function body).

Or, we could simply follow a consistent pattern of always using an enclosed function for any and all arrow functions.

const getSuperStuff = x => {
  return { x: x };
};
console.log(getSuperStuff(1));
// { x: 1 }

The last option is the safest, but is not popular with lazy folk (of which I am an active member).

comments powered by Disqus