JavaScript icon Get 69% off the JavaScript Master Bundle!

See the bundle then add to cart and your discount is applied.

days
hours
mins
secs

Ways to Return an Object from an Arrow Function

May 28, 2020 2 mins read

JavaScript post
JavaScript icon

Want expert JavaScript skills? Here's what you need to know.

Show Me View JavaScript courses

In this post you’ll learn a few different ways to return an object from an arrow function. Sometimes you’ll just want to return an object and not use any local variables inside the function.

Let’s explore some examples that’ll neaten up your codebase and help you understand further workings of the JavaScript language.

The most common and standard way of returning an object from an arrow function would be to use the longform syntax:

const createMilkshake = (name) => {
  return {
    name,
    price: 499
  };
};

const raspberry = createMilkshake('Raspberry');

// 'Raspberry'
console.log(raspberry.name);

This pattern is great, as it allows us to easily add some local variables above the return statement, a common practice for us.

But what if we don’t need to declare any local variables and just want to return an object?

We’ve heard of an arrow function’s implicit return feature - just delete the return statement and the curly {} braces right?

// ❌ Uncaught SyntaxError: Unexpected token ':'
const createMilkshake = (name) => {
  name,
  price: 499
};

And bam - a syntax error. This is what trips many developers up.

This is because the {} we’re expecting to be the opening/closing object braces have now become the function curlies as soon as we remove the return statement - the JavaScript parser acting as it should.

So, how do we solve it?

What’s interesting about JavaScript is its ability to create expressions using parentheses (). By doing exactly this and wrapping our intended object curlies in brackets, we create an expression and therefore return an expression.

This means that essentially the curlies are moved back “inside” the function and form the opening/closing object curlies once more:

// 👍 Perfect
const createMilkshake = (name) => ({
  name,
  price: 499
});

And that’s it. A really nice shorthand for returning objects from an arrow function.

Thankfully this ‘issue’ only applies to returning objects. For all other JavaScript types the implicit return works perfectly without this trick.

Exploring JavaScript Array Methods cover

⚡️ FREE eBook: 🔥 ForEach, Map, Filter, Reduce, Some, Every, Find

Todd Motto “This book is straight to the point, syntax exploration, comprehensive guide, real-world examples, tips and tricks - it covers all you need Todd Motto, author of Exploring JavaScript Array Methods

I hope you enjoyed the post, and if you’d love to learn more please check out my JavaScript courses, where you’ll learn everything you need to know to be extremely good and proficient at the language, DOM and much more advanced practices. Enjoy and thanks for reading!