0

I am taking a course on React Native and realize that the instructor declares functions in two different ways, for seemingly no different reasons. Please explain when each function declaration should be used:

example = () => ();

vs

example = () => {};

Thank you

The F
  • 3,647
  • 1
  • 20
  • 28
Devin Miller
  • 179
  • 1
  • 10
  • 1
    this `example = () => {};` needs a `return` inside in order to return something, otherwise it just executes code. this `example = () => ();` will directly return the expression inside round brackets – quirimmo Jan 14 '19 at 14:53
  • Basically, the first syntax specifies return value, second syntax executes code like any ordinary function. Please see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Dane Jan 14 '19 at 14:54

1 Answers1

2

Arrow functions can differ in function bodies (Thanks Robbie). The concise function body can only consist of a single expression which is evaluated and implicitly returned. The conventional block function body requires the return keyword or it will return void.

example1 = () => 1 + 1;

example2 = () => {
    const result = 1 + 1;
    return result;
};

example3 = () => { 
    const result = 1 + 1;
};

example1() has a concise body and will implicitly return the result of the expression 2.
example2() has a block body and does explicitly return 2.
example3() has a block body and no explicit return, therefore it returns void.

Note that the normal braces () around a concise function body are required if you want to return an object literal:

example = () => ({some: 'object'});
The F
  • 3,647
  • 1
  • 20
  • 28
  • here's a link to the MDN docs with this concept explained: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Function_body – Robbie Milejczak Jan 14 '19 at 16:27