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
Answers
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):(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
.Spread syntax is allowed in a handful of locations.
Change your code to:
Or this:
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:
This is based on assumption that the intention was
condition ? ...number[] : number
You can place
...
before a conditional operator without parentheses:Since
...
is a syntax (a syntax operates on results of expressions), operators are evaluated before it, a more explicit example: