Search code examples
javascripttypescriptsyntactic-sugartype-coercionfalsy

Coerce any nullish var into a bool in one command


In JavaScript we can coerce any variable into a boolean using either !!myVar or Boolean(myVar).

But these coercions are based on whether the value is falsy.

I wanted to know if there's a way to make it based on whether the value is nullish.

I know how to do it with "long" code:

if (myVar ?? true) {...

where the condition will be coerced into false only if nullish, and true otherwise.

But I want to know if it's possible to do it with just one operator like with the falsy case (something like

if (??myVar) {...

or so). Like "syntactic sugar".

I think it would make my code much cleaner and readable.


Solution

  • I'm affraid it's not possible. You have to keep using the nullish coalescing operator (??) or you could use your own function :

    function isNullish(x) {
      return x === null || x === undefined;
    }