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...?
How about this style suggestion: always prefer the object method notation. It requires explicit return-statements, and it leaves
thisalone.