Back in May, I wrote about three ways to write a function in JavaScript. One such way is to use an arrow function. I'd like to revisit those today: more specifically, using implicit return statements.

This is the example I used for an implicit return statement. It's a trivial function that adds two numbers together:

const add = (num1, num2) => num1 + num2;

We could have written the function like this:

const add = (num1, num2) => {
return num1 + num2;
};

But we didn't need to. Because the function just returns a value, we were able to use an implicit return statement.

For a tiny helper function like this, it's quite nice that we can move everything onto a single line. But if you want to return a longer value, this becomes impractical.

For example, let's look at this function from my Find the Monsters project:

function createMonster (monster) {
return (
"<li class='grid-item'>" +
"<img src='svg/" + monster.src + ".svg' alt='" + monster.alt + "'>" +
"</li>"
);
}

This function just returns a string. It doesn't do anything else. This means that if we converted it to an arrow function, we could use an implicit return statement. But could we?

First, let's convert it without the implicit return statement:

const createMonster = monster => {
return (
"<li class='grid-item'>" +
"<img src='svg/" + monster.src + ".svg' alt='" + monster.alt + "'>" +
"</li>"
);
};

We're now using an arrow function, but as you can see, it would be unreadable if we moved this onto a single line. And because we're still using the curly braces, we have to keep the return keyword. But there is a solution!

We can actually use the parentheses to wrap the value we want to return. This lets us drop the return keyword:

const createMonster = monster => (
"<li class='grid-item'>" +
"<img src='svg/" + monster.src + ".svg' alt='" + monster.alt + "'>" +
"</li>"
);

If we used a template literal instead of string concatenation, we could use the backticks instead of the parentheses:

const createMonster = monster => `
<li class='grid-item'>
<img src='svg/
${monster.src}.svg' alt='${monster.alt}'>
</li>
`
;

That's what I want you to remember:

When writing arrow functions, you don't have to put your implicit return statements on single lines. You just have to wrap them properly.