Search code examples
javascriptsyntax-erroroperatorsspread-syntax

Cannot use spread inside conditional operator


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.


Solution

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