Cannot use spread inside conditional operator

157 Views Asked by At

Suppose the following:

const arr = [1, 2, 3];
const insertValues = [-1, 0];
const condition = true;

arr.splice(0, 0, condition ? ...insertValues : insertValues);

This throws a syntax error:

Unexpected token '...'

I can get this to work by doing the following:

const arr = [1, 2, 3];
arr.splice(0, 0, ...[-1, 0]);

But this is obviously not what I'd like to do. How can I get the first example to work? I've tried including parentheses where I'd have thought necessary, to no avail.

4

There are 4 best solutions below

0
T.J. Crowder On BEST ANSWER

It would work if ... were an operator, but it isn't (and can't be), it's primary syntax. Operators can't do what ... does. Operators have to have a single value result, but ... doesn't.

So instead, you need to spread an iterable. You could do that by wrapping insertValues in [] when you want to insert it directly (your falsy operand to the conditional operator):

arr.splice(0, 0, ...(condition ? insertValues : [insertValues]));
// (Or you could use `unshift` if the index will always be 0 and you're never deleting anything)

(That may be what you meant later in your question. It's not an unusual idiom in cases where you want to use something as a series of arguments that may or may not be an iterable.)

Or just use an if/else.

0
Salman A On

Spread syntax is allowed in a handful of locations. Change your code to:

const arr = [1, 2, 3];
const insertValues = [-1, 0];
const condition = true;

arr.splice(0, 0, ...(condition ? insertValues : [insertValues]));

Or this:

if (condition)
  arr.splice(0, 0, ...insertValues);
else
  arr.splice(0, 0, insertValues);
4
Hao Wu On

If you don't want to bother with conditions and just want it work for both a number and an array, here's a solution that might be useful:

const arr = [1, 2, 3];
const insertValues = [-1, 0];
const condition = true;
arr.splice(0, 0, ...[insertValues].flat());

This is based on assumption that the intention was condition ? ...number[] : number

0
Alexander Nenashev On

You can place ... before a conditional operator without parentheses:

const arr = [1, 2, 3];
const insertValues = [-1, 0];
const condition = true;
arr.splice(0, 0, ... condition ? insertValues : [insertValues]);

console.log(arr);

Since ... is a syntax (a syntax operates on results of expressions), operators are evaluated before it, a more explicit example:

console.log([... 'a' + 'b']);