Proposal for a null coalescing operator

# Brandon Andrews (9 years ago)

en.wikipedia.org/wiki/Null_coalescing_operator

Essentially x ?? y will return x when not null or undefined else it will return y.

A nice Javascript explanation of the current problems with using || that can cause unforeseen bugs:

stackoverflow.com/a/476445

# Isiah Meadows (9 years ago)

This is something I frequently make a helper function out of.

function d(argument, default_) {
  return argument != null ? argument : default_
}
# Michael McGlothlin (9 years ago)

In JS it seems it'd be more useful if it worked with undefined not null.

Thanks, Michael McGlothlin Sent from my iPhone

# Kevin Smith (9 years ago)

A link to a wikipedia article is not actually a proposal : )

As Michael points out, you need to at least provide some consideration for null vs. undefined. I would also like to see some thought given to how such an operator might interact with a null propagation operator, discussed here:

esdiscuss.org/topic/existential-operator-null-propagation-operator

(Link appears to be temporarily not working...)

# Michael McGlothlin (9 years ago)

Another place JS would create a consideration is NaN. You might want that to play well with the operator. Possibly you could consider ?? for a wider range of nullish values and ??? for ONLY undefined.

x = parseInt ("a") ?? 42 x = a.nada ??? 42

📱 Michael McGlothlin

# Herby Vojčík (9 years ago)

Michael McGlothlin wrote:

Another place JS would create a consideration is NaN. You might want that to play well with the operator. Possibly you could consider ?? for

You've got || for "wider range of nullish values". Proposal (and, in my case, personally felt need) for ?? is to only cover null and undefined (== null) selection.

# Michael McGlothlin (9 years ago)

I'd probably do something like

x = y ?? ( parseInt(z) || undefined) ?? 42

Thanks, Michael McGlothlin Sent from my iPhone

# Kevin Smith (9 years ago)

I just noticed that null/undefined was addressed in the OP, my apologies.