In Perl I can say:
@a = ();
unshift @a; # @a is still ()
unshift @a, (); # @a is still ()
unshift @a, 1>0 ? 1 : 0; # @a is now (1)
unshift @a, 1>0 ? () : 0; # @a is still (1)
What, if it exists, is the JavaScript equivalent syntax?
a=[];
a.unshift(); # a is still []
a.unshift(...[]); # a is still []
a.unshift( 1>0 ? 1 : 0); # a is now [1]
a.unshift( 1>0 ? ...[] : 0 ); # syntax error
a.unshift( 1>0 ? (...[]) : 0 ); # syntax error
a.unshift( 1>0 ? [] : 0 ); # a is now [[],1]
In Perl I can say:
@a = ();
unshift @a; # @a is still ()
unshift @a, (); # @a is still ()
unshift @a, 1>0 ? 1 : 0; # @a is now (1)
unshift @a, 1>0 ? () : 0; # @a is still (1)
What, if it exists, is the JavaScript equivalent syntax?
a=[];
a.unshift(); # a is still []
a.unshift(...[]); # a is still []
a.unshift( 1>0 ? 1 : 0); # a is now [1]
a.unshift( 1>0 ? ...[] : 0 ); # syntax error
a.unshift( 1>0 ? (...[]) : 0 ); # syntax error
a.unshift( 1>0 ? [] : 0 ); # a is now [[],1]
Share
Improve this question
edited Mar 4 at 13:32
brian d foy
133k31 gold badges213 silver badges605 bronze badges
asked Mar 3 at 14:07
jhncjhnc
17.2k2 gold badges14 silver badges32 bronze badges
8
|
Show 3 more comments
1 Answer
Reset to default 3You cannot use the spread syntax where you have it, as an operand of the conditional (ternary) operator. Instead inverse the order of the spread syntax and the conditional operator and make sure the conditional operator always evaluates to an iterable -- so provide [0]
instead of 0
:
a.unshift(...(1 > 0 ? [] : [0]))
As Mozilla Contributors wrote:
the spread (
...
) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.
The operand of the conditional operator is not such a place as exactly one operand is expected between the ?
and :
symbols.
a.unshift( 1>0 ? (...[]) : 0 );
supposed to do? Do you understand what...
does? – luk2302 Commented Mar 3 at 14:12a.unshift( ...(1>0 ? [] : [0]) );
– luk2302 Commented Mar 3 at 14:16unshift @a, 0 if 1 > 0;
andif ( 1 > 0 ) a.unshift( 0 );
are a lot clearer, though. – ikegami Commented Mar 3 at 15:49