Notes of Maks Nemisj

Experiments with JavaScript

Implicit return in arrow function got me…

I still have to 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 this two ‘almost’ identical parts of code and think 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 statement in the body, whenever there are no curlies, it sees it as expression and applies 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.

,

2 thoughts on “Implicit return in arrow function got me…

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.