I was just hacking away on a side project when I wrote this code:
const screencastMock = {
findOne: () => { }
};
My intention was to make findOne
return an empty object literal ({}
) but it actually returns undefined
.
Can you spot my mistake?
When JavaScript sees () => { }
, it interperts the { }
part as a block statement instead of an empty object literal:
const screencastMock = {
findOne: () => { var insideABlockStatement = true; var owned = true; } // valid JavaScript!
};
The block statement doesn't contain a return statement so this
is implicitly returned. In this context, this
was undefined
, hence why findOne
returns undefined
.
To successfully return an empty object literal, I should have surrounded the empty object literal in parentheses, like this:
const screencastMock = {
findOne: () => ({})
}
I found this error amusing because I'm well aware of this caveat with arrow functions and yet it still tripped me up 😆! If I wasn't aware of this caveat, who knows how long I could have been stuck here...
I wounder if there's an ESLint plugin available to help avoid this mistake...?
I don't really get what's the big deal here.
You wrote:
function() {}
and expected an object literal in return? Ookay.But thanks for the
({})
tip, I'll probably never use it but it's a cool thing to know.