Ecmascript 6 arrow function that returns an object
The magic trick to creating an object from an arrow function is to encase the object in parentheses. This makes it distinct from a function block and poof – disappears the need for a return
statement.
This design is efficient, clean, a magician's dream, and instantly produces the object you seek.
Unwrapping the mystery of arrow function objects
Know when to hold 'em, know when to return
'em
When dealing with single expressions, arrow functions automatically, or implicitly, return the value of the expression without needing the return
keyword. To return an object literal, wrap it in parentheses to avoid it being treated as a block body.
More than just one trick
Sometimes one trick isn't enough, and you need more than a single expression. You can perform multiple statements within a block body {}
, but make sure to use an explicit return
.
Master illusionist or simple mistake?
Never confuse your audience, or a block body { } with object literals { }. A classic mistake often made by apprentices and not masters. Always use parentheses when returning an object to make your intentions clear!
How to mystify and amaze with objects
Magical shorthand property names
When you've got too many pigeons in your sleeves and the variable names match the object property names, you can use shorthand property names to keep your act running smooth and quick.
Destructuring for the big reveal
One of the most breathtaking aspects of arrow functions is how elegantly they perform parameter destructuring. Arrow functions allow you to directly extract properties from objects passed as arguments.
Transpiling to keep the show going
Everyone loves a showstopper, but need to keep your tricks compatible for the entire crowd. Even the old geezers who still use ES5. Sophisticated tools like Babel can help transpose your functions, but pay heed to the celestial syntax during the process.
The grand finale: Getting it right
The guide to performing flawlessly
The MDN documentation is every magician's grimoire, giving you the spells, incantations, and use cases, not to mention the limitations, and differences between the old and new magic that is arrow functions.
Staying in touch with the mystical arts
It's important to stay updated with the ever-evolving world of JavaScript. Arrow functions, brought to us by the arcane arts of ES6, is a paradigm shift in the craft that everyone should learn.
The power of community and camaraderie
Fellow sorcerers and soothsayers have compiled a treasure trove of tricks and hexes that will help grasp the nuances of the craft better. Don't hesitate in exchanging and experimenting with spells and code snippets in your pursuit of perfection.
Was this article helpful?