Nullish unary operator `?`

The argument for conciseness probably won't get this idea far, == null is a commonly used exception to the "no loose equality" rules and is already pretty concise. I doubt an operator whose primary purpose is to shave off a few more characters would get very far.

The argument that adding this operator would make this language less confusing for new-comers is much stronger. It is easier to explain to newer people to never use loose equality, and to use an operator like this for null/undefined checking, as opposed to explaining to them to "Don't use loose equality, except when doing a null/undefined check - then it's okay to use == null - it doesn't look like it, but == null will check both null and undefined, and nothing else."

I don't know if this argument is strong enough to warrant additional syntax. But maybe it is strong enough to warrant an additional function, i.e. isDefined(someValue) - this won't provide a more concise syntax that @Clemdz lemdz wanted, but it does help with onboarding new developers into the language. With projects with lots of newer developers, it's easy enough to just ban loose equality and have them use this function to check for null/undefined. For projects with more seasoned developers, they could potentially choose to mostly ban loose equality, except for the == null case, which is slightly more concise. But more seasoned developers might still prefer isDefined() because it's less magical and more clear.

If we choose to go forwards with the ? operator - My preference is that it is a postfix operator, coffeescript style.

if (data.user.address?) { ... }

It reads better to me, but I guess that's a completely subjective point of view.

1 Like