What is the difference between keys and parentheses in an Arrow Function in Javascript?

Asked

Viewed 598 times

10

What is the relevant difference between keys ({ }) and parentheses (( )) in a return of a function?

const example = () => ( ... );

Versus:

const example = () => { ... };
  • Bracket will return the last instruction. Key will not return anything. Unless you set with return, as in any function/method...

  • If you want to write an answer, example, etc ... @Lipespry

  • 1

    I do this tomorrow if no one formulates an answer. That’s why I commented "the relevant". I’m passing by.

  • 3

    I think it is worth changing the title of the question to "What is the difference between {} and () in an Arrow Function in Javascript", since this is not a resource exclusive React, but Javascript. What do you think? :)

  • @Luizfelipe made the change.

  • Brackets or parentheses?

  • () => ( ), so empty, is syntax error... or doubt is with something inside ()?

  • @sam edited and thank you.

  • @Sergio is not empty ... is with instruction, how will behave, thank you.

Show 4 more comments

3 answers

12


First of all, it is worth noting that this is not something exclusive to React. It is a syntactic feature of Javascript. It was introduced in Ecmascript 2015 (ES6), with the addition of Arrow functions. Among the various features introduced by this new way of creating a function, one can cite the evaluation of a code block or a single expression.


Older methods for defining functions in Javascript require you to necessarily create a block. For example:

function doStuff() {
  // Eu sou um bloco!
}

const doOtherStuff = function() {
  // Eu sou um bloco!
};

As Arrow functions, on the other hand, no. Allow the developer to choose to use a single expression. If necessary, of course, blocks can still be used to be the body (body) of Arrow Function.

So if your Arrow Function returns something between parentheses (), means that your body is a single expression, which will be evaluated during your invocation. Note that it is not necessary to use parentheses to denote an expression. In this specific case, usually the parentheses are placed in expressions that will occupy multiple lines, such as several JSX components, which are expressions, since, in the background, they are only calls to React.createElement.

const fn1 = () => 'Hello, world!';

const fn2 = (x, y) => x + y;

const fn3 = (x, y, z) => (
  x +
  y +
  z
);

console.log(fn1());
console.log(fn2(1, 2));
console.log(fn3(1, 2, 3));

If already the Arrow Function has been defined with keys ({}), your body will be a block, which can execute multiple expressions and statements (statements). In this case, the function will return a value explicitly defined through the return. Otherwise, undefined will be returned.

Some examples of Arrow Function whose body (body) be a block:

const fn1 = () => {
  return 'Olá, mundo!'
};

const fn2 = (x, y) => {
  // `if` é um exemplo de declaração (statement):
  if (x > y) {
    return 'X é maior que Y.';
  }
};

console.log(fn1()); // Olá, mundo!
console.log(fn2(9, 1)); // X é maior que Y.
console.log(fn2(1, 9)); // undefined

Although this was not put in the question, it is worth remembering that the parentheses can also be used to group several expressions (separated by commas), evaluating one by one but returning only the last one. See more on documentation.

For deepening, I suggest reading of this chapter the excellent book "Javascript for impatient programmers", which covers the differences between expressions and statements.

  • 1

    You finished the answer in half of mine, but I put it anyway because of the last item you didn’t mention, I’ve had problems with it and it took me a while to understand the mistake

7

This has nothing to do with React, JSX or any library or superset (Typescript, for example), are just Javascript syntax:

In the second, the keys define the beginning and end of a block of code, which can have multiple expressions and other blocks of code, separated by ; or line break:

() => {
   foo();bar()
   for (const fun of functions) {
       fun()
   }
}

When defining keys, the function will not return anything (ie, undefined) unless done explicitly with the keyword return

To first is just a parenthesis to group an expression, which will be returned by the function, so () => (qualquercoisa) is equivalent to () => qualquercoisa, is usually used to make clear the beginning and end of the expression:

() => (
    <div className="alert">
        <p>Um exemplo qualquer</p>
    </div>
)

If you want to return a literal object, its use is necessary so that the keys are not confused with the beginning and end of the code block, which would generate a syntax error:

// Correto
() => ({
    foo: 'bar'
})

// Erro
() => {
    foo: 'bar'
}

2

Both previous answers already define the difference well. Only one question remained to be highlighted:

When using parentheses, automatically the last expression will be returned.

Example:

var a = 10;
var b = 10;
var c;
var d;

var foo = () => (c = a+b, a);
console.log(foo()); // define o valor de 'c' retorna 'a' (10)
console.log(c) // 20

var bar = () => (d = a+b, c = d+a, d);
console.log(bar()); // define o valor de 'd', 'c' e retorna 'd' (20)
console.log(c); // 30

When one wants to return only one expression, it makes no sense to use the parentheses. It becomes a matter of aesthetics.

Example:

var a = 10;
var b = 10;

var fuba = () => a+b;

console.log(fuba()); // 20

It is also worth mentioning that if you have more than one expression without delimiting with parentheses, the first will be returned despite executing the other.

Example:

var a = 10;
var b = 10;
var c;

var foo = () => c = a+b, a = 50;

console.log(foo()); // define o valor de 'c' (a+b), 'a' (50) e retorna 'c' (60)
console.log(c) // 60
  • I think it’s worth mentioning that it’s not the parentheses that create this behavior of returning the last expression. That’s an operator’s ability , (comma Operator). Learn more here.

  • @Luizfelipe very well placed! But if you use parentheses, it is good to know that the last expression will be returned. Right? Any small detail helps the reader.

  • Yes, it is something that helps to understand, although the behavior is caused by the comma, and not by the parentheses. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.