Literal array and "conditional" element inclusion

11 views
Skip to first unread message

Mike Austin

unread,
Apr 9, 2021, 11:55:49 AM4/9/21
to PiLuD
In JavaScript, you can conditionally include an element in a literal array, but the syntax is a bit wonky using the spread operator:

const menu = [
  { type: 'item', title: 'Dashboard' },
  ...(config.url !== null ? [{
    type: 'item', title: 'Applications'
  }] : [])
,
]

You basically spread (...) the expression of an array with the element, or an empty array. It feels similar to mapping over Option, maybe?

What better syntax could there be?

Mike Austin

unread,
Apr 9, 2021, 12:31:10 PM4/9/21
to PiLuD
I found in Ruby you can do this:

[*(str1 unless str1.empty?), str2]

"If that were the end of the story, it wouldn't be very useful. But splat has another peculiar ability. It can intelligently coerce objects into arrays."

# Usually `*thing` wraps `thing` in an array
x = *"hi mom"
# => ["hi mom"]

Ruby turns the expression into an array, then "splats" it back. I'm not sure if that is too "magical", or makes complete sense. It's definitely useful.

Raoul Duke

unread,
Apr 9, 2021, 12:33:32 PM4/9/21
to pi...@googlegroups.com
might as well be writing perl.

Mike Austin

unread,
Apr 9, 2021, 1:02:49 PM4/9/21
to PiLuD
Yeah, maybe that's too "magical". I generally do like the spread/splat operator, though:

[first, *rest] = ...
[*rest, last] = ...
[first, *rest, last] = ...

{ ...props,  a: 1 }

Vs literal record update syntax in some languages.. with spread you can combine/updates as many as you need.

Raoul Duke

unread,
Apr 9, 2021, 1:17:14 PM4/9/21
to pi...@googlegroups.com
splat in JS seems not too bad although i fear wtf is going on under
the covers. "the value of everything, the cost of nothing" comes to
mind. and using it to delete things from an object is like One Weird
Trick gross.

things like varargs, i have NEVER seen done well anywhere. ditto i
mostly find syntax for default arg values to be dog sh*t ux overall.

i kinda don't like programming languages :-)
Reply all
Reply to author
Forward
0 new messages