Search code examples
javascriptecmascript-6arrow-functions

Arrow function with multiple statements in one line


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?


Solution

  • 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.