[Proposal] Optional chaining

# Beknar Askarov (5 years ago)

Problem

Spreading is great! It contributes towards "declerativity" of the language and reduces verbosity. I see one more feature to add to improve it.

Consider following

[ 1, condition && 2, condition && 3, 4, ].filter(Boolean) // filtering needed to remove falsy values // Results in [1, 2, 3, 4] // if condition is truthy// and [1, 4] // if not truthy.

Another way to achieve the same result without the need of filtering after

[ 1, ...(condition ? [2, 3] : []), // note extra [] in the end, to avoid errors 4, ]

Similar pattern with objects

{ ...(condition ? { foo: 'bar' } : {}), // extra {} }

Another pattern is when condition is the object itself, when it is known that type is one or falsy

[ item1, item2, ...(itemsOrNull || []) // extra [] ]

Similar for objects

{ ...(obj || {}), // extra {} }

I see these patterns appearing very often. And these are cleanest examples I have seen so far. ProposalOptional spreadingWith condition

// Arrays [ 1, ?...(condition && [2, 3]), // no extras:) 3, ]// Objects { ?...(condition && { foo: 'bar' }) // no extras:) }

When condition is the object

[ item1, item2, ?...itemsOrNull // no extras at all:) even (...) ]

These look nicer and can be good for performance since (?...), since no cleanup is needed after to remove falsy values or extra spreading even when it is not needed.

Looks intuitive (since: tc39/proposal-optional-chaining) Plays nice with typeings.

What do you think? es.discourse.group/t/optional-spreading/93

# Michael Luder-Rosefield (5 years ago)

Another similar thing I've used is with String interpolation; if you use a similar pattern, e.g.,

`$[items.length} item${items.length !== 1 ? 's' : ''} in collection`

When you want to conditionally add either some text, or nothing at all, you are forced to use the ternary with an empty string, or some workaround. In terms of a proposal, the first thing I think we need to know is: can the interpreter detect that it's in a template literal, in the same manner as it detects ?... being in an object/array declaration context?

Dammit babies, you've got to be kind.