Nullish Ternary Operator

On GitHub: GitHub - K-E-L/Nullish-Ternary-Operator

Motivations

There are no good ways of resolving a conditional to a nullish value as they resolve to a truthy value by default. The nullish ternary will resolve the conditional to a nullish value without needing the extra syntax necessary to make this possible.

Details

A regular ternary looks like this and solves the condition based on truthiness

(condition) ? expression_if_truthy : expression_if_falsey

The proposed nullish ternary will look like this and solves the condition based on nullishness

(condition) ?? expression_if_not_nullish : expression_if_nullish

Current Implementations

I see no good ways of doing this in the current ECMAScript standard as they either don't account for the "else" clause or don't accomplish the task in a clean way. If I'm missing any ways that this can be done without the proposed nullish ternary please let me know.

It could be done using an AND statement with the condition referenced twice but this could be done better.

(condition !== null && condition !== undefined) ? expression_if_not_nullish : expression_if_nullish

A nullish coalescing operator could be used but wouldn't be able to evaluate the expression_if_not_nullish.

(condition ?? expression_if_nullish)

Or it could be done with a hash but this is very awkward and would assume the condition doesn't evaulate to the long_hash_value.

((condition ?? long_hash_value) !== long_hash_value) ? expression_if_not_nullish : expression_if_nullish

Obstacles

The reason this might not be possible is because ?? is already being used as the nullish coalescing operator while the ? did not have a previous coalescing meaning. This will prove difficult especially when trying to implement ternary chaining. Hopefully, these problems will not prove too difficult and a clean way of resolving conditionals for nullishness can be accomplished.

1 Like

What's wrong with

(expression != null) ? expression_if_not_nullish : expression_if_nullish
1 Like

Oh, I guess that does work. Thanks for pointing that out. I still feel like there should be a way to resolve the expression itself without the appendage of "!= null" but maybe that's just me. Maybe it does make more sense to more people to say "!= null".

document.all, I guess, although that's just being really pedantic.

1 Like

This idea could also be used to solve this particular use-case. The suggestion there is to introduce a ? operator, that returns true if the input value is not nullish, and false otherwise.

You could combine this with the ternary operator to achieve the desired effect:

?expression ? expression_if_not_nullish : expression_if_nullish
2 Likes

For ensuring that pesky document.all doesn't throw a spanner in the works...

((x ?? null) !== null)

:sweat_smile: