All Articles

Implicit Return in JavaScript Arrow Functions

JavaScript functions can do all sorts of things for us. Often, we need them to return a value, whether it’s a string, number, Promise, or a large, complex object. With functions declared using the function keyword, we must always use the return keyword to do this.

function addTwo(num) {
  return num + 2;
}

We can write arrow functions with similar syntax:

const addTwo = num => {
  return num + 2;
};

We can also write this using the implicit return syntax:

const addTwo = num => num + 2;

As you can see, implicit return is so named because it returns a value without our declaring that the value is returned explicitly.

Some folks like implicit return, some hate it - but it’s here to stay in JavaScript, and chances are that you’ll run into it in codebases that you work in, so it’s good to get familiar.

The benefit of implicit return is mainly that it is more concise. Arguments against its use are that it makes code intent harder to understand (it is, after all, less explicit), and that it makes refactoring more difficult.

Implicit return statements can be useful in array method callbacks, like so:

const people = [
  {
    name: "Samuel",
  },
  {
    name: "Samantha",
  },
];

const peopleNames = people.map(person => person.name);

This reads nicely compared to the return keyword alternative:

const peopleNames = people.map(person => {
  return person.name;
});

Implicit return can be used with plain objects, but they must be wrapped with parentheses to distinguish them from a function block, like so:

const getCompanion = () => ({
  name: "Sparky",
  breed: "Golden Retriever",
});

Implicit return can also be used with React components, if they don’t require any variables to be declared. In React, it looks like this:

const Message = ({ message }) => <div>{message}</div>;

I’ve seen this syntax’s merit debated at length in code reviews and on Twitter. I personally like it for some use-cases. Whether you like it or not, I hope this post has helped you to understand it a bit better!

Read more about arrow functions on MDN