Nullish unary operator `?`

Thanks for your feedback @theScottyJam!

I totally agree on what you said about loose equality confusion by new-commers.
Loose equality is one the most awkward feature of javascript, and if we could get rid of it definitively (if only!), I think that would be for the better.

Concerning using the operator as a postfix, I wasn't aware it was actually a thing in coffescript! :)

When I was thinking about the operator design, I was also hesitating between prefix and postfix, because
if (a?)
can be better read as "if a defined", compared to
if (?a)
("if defined a")

At the end, I still decided to go for the prefix version for the following reasons:

  1. it is used the same way than the ! operator, so the syntax is already intuitive:
// Logical NOT operator
if (!a) { // if falsy }

// Unary Nullish Operator
if (?a) { // if not nullish }

However, if we're comparing the two operators, it's good to note that ! will return true for falsy value, whereas ? will return true only for non-nullish values (0, "", NaN, ...). So the ? operator has nothing to do and should not be summarized with: "a ! operator but that only works with nullish values"

  1. It is quicker to see what's going on (might be subjective):

Having the operator at the end of the variable, you realize that you are evaluating whether the variable is defined (and not the variable itself) only at the end of the condition

if (data.user.address?) {} // you could first read it as: `if (data.user.address)` before seeing the `?` at the end

whereas when it's in prefix position, you directly understand that you are checking whether the variable is defined or not:

if (?data.user.address) {} // you know from the first character what's happening

So maybe that's a small detail, maybe you don't necessarily agree, but that's still something I wanted to care about.

  1. It still looks clean when using negation:
// prefix version
if (!?data.user.address) {}

// postfix version
if (!data.user.address?) {} // it's a bit trickier to read

// The negative postfix version works better in coffeescript
// as there is a `not` operator that makes it look cleaner
if (not data.user.address?) {}
// but this only work in coffeescript, so is this not really pertinent here

But at the end, as @aclaymore pointed out, the postfix version could potentially be parsed as a ternary operator in some special cases, which would break backward compatibility :(

The only way to have this as a postfix operator, like in Coffeescript, would be to use another syntax than ?, but then it would no really be like coffeescript anymore.

2 Likes