0

Recently I found out that a simple arrow function, for example callback in this map

[1, 2, 3, 4, 5, 6].map(item => {
    console.log(item) // or anything else
    return item - 1;
})

I can re-write to one line command like this

[1, 2, 3, 4, 5, 6].map(item => (console.log(item), item - 1))

I can use as much statements I want to devided by , and last argument will always be a return value. It looks kind of cool to me, but cant find anything about this syntax in arrow function documentation. Can anyone explain this syntax or just point to place where I found a docs?

l2ysho
  • 1,288
  • 12
  • 28

2 Answers2

0

Essentially it allows you to do multiple operations in a single statement. It's used commonly in for loops and to assign multiple variables in a single statment, eg.: var a = 1, b = 2;.

Just because it works though, doesn't mean it's a good idea. It makes your code less readable and harder to debug.

See the MDN docs on the Comma Operator.

The comma operator (,) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions. This is commonly used to provide multiple parameters to a for loop.

I wrestled a bear once.
  • 19,489
  • 16
  • 63
  • 110
  • Sure it is not good Idea :) I just never saw a comma operator used in this way, so I have been little confused – l2ysho Aug 17 '20 at 18:30
  • 3
    _"It's used commonly... to assign multiple variables in a single statement"_ That's technically wrong. The `,` token in a [declaration statement](https://www.ecma-international.org/ecma-262/#sec-declarations-and-the-variable-statement) is not the [comma operator](https://www.ecma-international.org/ecma-262/#sec-comma-operator), they're actually defined separately in two different parts of the grammar. – Patrick Roberts Aug 17 '20 at 18:35
-1

You are using the comma operator to evaluate multiple expressions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator

Nils Schwebel
  • 576
  • 2
  • 12