Why you might accidentally get an undefined value returned from a function when trying to return an object literal.
Do you know the what is returned from the following?
Here’s a hint:
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:
returnoccurring on its own line causes the program execution to return without proceeding further
Prettier can help you catch this error if you have semicolons turned on.
In that case, prettier will automatically drop a semicolon after
I usually keep my semicolons turned off, and I prefer arrow functions, so this is something that can come up frequently in my code.
The fix is in
This is how we would fix the first example:
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.
- The book ExploringJS by Dr. Axel Rauschmayer has a whole chapter discussing Arrow Functions in depth:
13. Arrow functions
There are two benefits to arrow functions. First, they are less verbose than traditional function expressions: Second…
- Manuel Rauber overviews returning object literals on his blog:
Returning object literals from arrow functions
Quick object return is maybe a not-so-well-known feature, because you don't see it that often. And it's not a new…
- Tim Kamanin includes an example using
.map()on his blog: