JavaScriptJavaScript

Returning Object Literals from Arrow Functions in JavaScript (ES6)

Mar 25, 2018 · by Tim Kamanin

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:

javascript
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:

javascript
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?":

javascript
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:

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

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

That's all, hope it helps!

Hey, if you've found this useful, please share the post to help other folks find it:

There's even more:

Subscribe for updates

  • via Twitter: @timonweb
  • old school RSS:
  • or evergreen email ↓ ↓ ↓