This page looks best with JavaScript enabled

Implicit return gotcha for arrow functions

 ·   ·  ☕ 2 min read

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.

1
2
3
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.

1
2
3
4
5
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 -

1
2
3
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.

1
2
3
4
5
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).

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things