Conditionally add elements to declaratively defined arrays

@ljharb I think that in all of your examples you are missing the point of what the folks here are expressing.

There’s an interest in having a more concise syntax to express the pattern of conditional elements.

I personally like some of the proposals made here. It’s syntactic sugar for something that can be done in the language but I think they help by reducing the number of symbols your eyes have to parse. I know readability can be subjective but I equate less symbols with less effort to read.

I’ll just add that the pattern of conditional elements in arrays comes up often when writing plugins/presets for certain tools (babel, webpack, etc) when based on some option you may conditionally add items to an array that is part of a config. I’ve used the pattern …(a ? [b, c] : []) in many of these cases.

I'm not missing the point :-) I appreciate the value of syntactic sugar.

I'm trying to point out that the current pattern "to beat" - to justify the inclusion of syntax, the most expensive thing - is along the lines of [].concat(x, y || [], z ?? []).

In order to justify adding syntax, the proposal would have to be better in more ways than just ergonomics: easier to do right/harder to do wrong; easier to do performantly; a frequent enough operation that the DX impact is significant - to name a few.

Out of those four, I'm not convinced that any apply here besides "ergonomics".

@ljharb ok maybe I misread your previous comments but I find your last comment a lot more helpful because it is more direct. And thanks for explaining your position.

I suppose I don't have much to support the “easier to do right/harder to do wrong”

But aren’t there performance improvements tactics that this would enable?

  • avoid creating intermediate arrays (better memory usage)
  • allocate the array size upfront (instead of relying on resizing the underlying memory block)
  • avoid prototype lookup

Maybe these are small things - its hard for me to quantify the impact of these things but am curious if any of these points resonate with you.

1 Like

I’d be surprised if any of those made a difference, but it’d probably take an engine implementer to know for sure.

I agree @GeorgeTaveras1231. …(a ? [b, c] : []) is allocating an array just to spread it and then immediately free it. That's pretty wasteful