Why you might accidentally get an undefined value returned from a function when trying to return an object literal.

Dr. Derek Austin 🥳
Sep 17 · 3 min read
Photo by Joe Pregadio on Unsplash

Pop quiz

Do you know the what is returned from the following?

Here’s a hint:

Photo by Mike Dorner on Unsplash

Amazingly, JavaScript will print undefined in this situation.

Let’s look at how it would work with an arrow function:

This code results in the same outcome (undefined) for two reasons:

  1. return occurring on its own line causes the program execution to return without proceeding further
  2. JavaScript uses curly brackets { } for both block statements and object literals.

Prettier can help you catch this error if you have semicolons turned on.

In that case, prettier will automatically drop a semicolon after return:

I usually keep my semicolons turned off, and I prefer arrow functions, so this is something that can come up frequently in my code.

Photo by Lysander Yuen on Unsplash

The fix is in

This is how we would fix the first example:

Simply moving the opening curly brace up to the same line as the return lets the JavaScript parser know to return an object literal.

And with arrow functions, we need a set of magic parentheses:

Behind the scenes

The magic parentheses force the parser to treat the object literal as an expression instead of a block statement.

When the parser finds parentheses around the entire body of the object literal (an expression), it is not treated as a block statement (not an expression).

According to the ECMAScript specification, block statements cannot be parenthesized, so the opening parenthesis signals the start of an expression.

Photo by Nick Fewings on Unsplash

Additional resources:

  • The book ExploringJS by Dr. Axel Rauschmayer has a whole chapter discussing Arrow Functions in depth:
  • Tim Kamanin includes an example using .map() on his blog:

JavaScript in Plain English

Learn the web's most important programming language.

Dr. Derek Austin 🥳

Written by

😀 Full-Stack Web Developer 🤓 JavaScript 😄 React 😁 React Hooks 😆 Jest 🥰 CodeSandbox.io Contributor 🧠 Mobile App Developer 🤳 Doctor of Physical Therapy 🆒

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade