Simple question: Is there a way to use an expansion inside a conditional statement using the ternary operator?
const a = 1, b = 2;
// Works
console.log(...[ a, b ]);
// Works
console.log(...(a ? [ a, b ] : [ 'Not found' ]));
// Doesn't work
console.log(a ? ...[ a, b ] : 'Not found');
Unfortunately this isn’t currently possible. The …
spread syntax, like its name tells us, is a part of the syntax of the language and not a ‘normal’ operator that deals with expressions (à la +
or typeof
). The ternary operator needs expressions after the ?
and :
, so you can’t use the syntax in those spots.
You’ll have to do e.g.
condition
? console.log(…)
: console.log(…)