Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Implicit Returns in the Arrow Function Got Me…

DZone's Guide to

Implicit Returns in the Arrow Function Got Me…

It may take longer to write, but writing out explicit return statements will save time in the long run.

· Web Dev Zone
Free Resource

Get deep insight into Node.js applications with real-time metrics, CPU profiling, and heap snapshots with N|Solid from NodeSource. Learn more.

I still have to get used to this new arrow functions and implicit return statement. If you’re unfamiliar with them, here is the doc – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Look at these two ‘almost’ identical pieces of code and tell me, what is the difference between them?

code-one.js

function run(context) {
  return methodOne()
    .then(() => doIt(context) );
}

and this one:

code-two.js

function run(context) {
  return methodOne()
    .then(() => { doIt(context); });

They look the same, except that one will work correctly and another one won’t. Whenever an arrow function has curly braces, it expects a statement in the body. Whenever there are no curlies, it sees it as an expression and applies an implicit return to it.

It’s quite easy to overlook this when doing code review or writing code at two o’clock in the morning. That’s why I suggest to not write implicit code like this. Stick to the explicit return statement and you’re safe. I know, it’s longer to write, but remember: “Time saved by less typing is not comparable to the time spent on debugging this code.”

You’ve been warned.

Node.js application metrics sent directly to any statsd-compliant system. Get N|Solid

Topics:
javascript

Published at DZone with permission of Maks Nemisj, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}