Returning Object Literals from Arrow Functions in JavaScript (ES6)

25 Mar · by Tim Kamanin · 2 min read

ES6 update brought us the arrow functions, a great tool to make our code look elegant.

One of my favorite features of this additions is the ability to create slick one-liners, like this:

const numbers = [2, 3, 4];
const squares = numbers.map(n => n**2);

// Result:
// [4, 9, 16]

This works, until you want to return an object. You see, we use brackets {} to create objects, and if we'll try to return an object via one-liner:

const numbers = [2, 3, 4];
const squares = numbers.map(n => { result: n**2 });

// Result:
// [undefined, undefined, undefined]

We'll get an array of undefined values. Why? Because, when we open brackets, arrow function sees it as a block opening and expects us to return a value via explicit return.

So, you may ask "is all we can do here is to explicitly return objects, like this?":

const numbers = [2, 3, 4];
const squares = numbers.map(n => { return {result: n**2} });

// Result:
// [{result: 4}, {result: 9}, {result: 16}}]

Nope, we can still return objects implicitly with one-line arrow functions with the help of parenthesis (). We just need to wrap with parenthesis the object literal we want to return.

Here's a working, more closer to life example:

const hockey2018Winners = [
  'Russia', 'Germany', 'Canada'
]

const winners = hockey2018Winners.map((team, index) => ({name: team, place: index + 1}))

That's all, hope it helps!

Want to get more 🔥 tips like this one?

Subscribe to get notified about new dev tutorials

Comments