Optional projection / expression operator - e.g. maybeNullish ?:: transform(maybeNullish)

Nullish coalescing and optional chaining/evaluation are great, but one analog is still missing--
being able to short-circuit when the nullable value is in an argument position.
e.g. in a template string, passed to a function, used with arithmetic operators, etc.

Currently still need to use null checks and ternaries like

(val !== null && val !== undefined) ? transform(val) : undefined

or

(x != null &&  y != null) ? `${x} ${y}` : undefined

I'd like to suggest an operator to simplify this pattern that evaluates the right hand expression only if the left hand value is defined, and resolves to undefined otherwise

e.g.

val ?:: transform(val)
x ?:: y ?:: `${x} ${y}` //this would be ok if evaluated l-r right?
(a ?:: a + 2) ?? 0  // in combination with nullish coalescing

Side thought:
I tried to think of a clean way for aliasing the LHS value if it is not a simple identifier, but had less success. Ultimately thought maybe an expression-local aliasing operator would be needed.

someFunction()::x ?:: `${x} and a suffix`
//edit: optional pipelining as suggested in the other thread is probably a better solution for this one.
someFunction() ?> (x => `${x} and a suffix`)

(sorry for all the edits >,<)

Are you aware of the nullish coalescing operator, ??, which landed in ES2020?
https://github.com/tc39/proposal-nullish-coalescing

Yes, this suggestion is for one of the cases not covered by the new nullish/optional operators...
the case where the nullable thing is in an argument position / used in an expression that only applies when defined. (i edited the original post to clarify)

Template strings based on the nullable value are one of the simplest examples.

This other thread may be of interest:

3 Likes

Beat you to the punch: https://github.com/tc39/proposal-pipeline-operator/issues/159 :slightly_smiling_face: