5

In JavaScript it's possible to merge array with another using the ... (spread) operator as follows

[...[1,2,3], ...[4,5,6]]
// -> [1, 2, 3, 4, 5, 6]

However, it seems ineligible to use the spread operator inside ternary ? expression

[true ? ...[1,2,3] : ...[4,5,6]]
// Uncaught SyntaxError: Unexpected token ...

Is this a justified restriction in the language, a deficiency or am I missing something? Is is possible to achieve this syntactically without imperative approach or Object.assign() function?

Charlie Harding
  • 653
  • 8
  • 22
Tuomas Toivonen
  • 21,690
  • 47
  • 129
  • 225
  • _"**Spread syntax** allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected."_ ([Source](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)) – Andreas Jan 21 '19 at 16:34

1 Answers1

11

Move the dots outside of the expression and perform the spreading with the result.

console.log([...(true ? [1, 2, 3] : [4, 5, 6])]);

This works only with values who are spreadable. If not, wrap the not spreadable part into an array.

console.log([...(true ? [1] : [4, 5, 6])]);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392