Since we all know null is evaluated as false, how could I write "is null or true" in Javascript? I have tried:
function isNullOrTrue(nullableBool){
return !(nullableBool != null && nullableBool != true);
}
Is there a better way to do this?
Since we all know null is evaluated as false, how could I write "is null or true" in Javascript? I have tried:
function isNullOrTrue(nullableBool){
return !(nullableBool != null && nullableBool != true);
}
Is there a better way to do this?
If the three possible inputs are only null
, true
and false
, you can use
return nullableBool !== false
but explicitly listing the matching values isn't bad for readability either
return v === null || v === true
Using ===
instead of ==
isn't actually necessary here, as null != false
(whereas Boolean(null) == false
), but it might help for clarity if you're not familiar with the loose equality rules.
The elegant solution to is null or true
is to use nullish coalescing operator
return nullableBool ?? true
It will return true if nullableBool
is either null
or undefined
. Otherwise, it will return the value of nullableBool
. If you only want to return true
or false
, then you can use double bang:
return !!(nullableBool ?? true)
Now, it will return true
if nullableBool
is either null
, undefined
or truthy value. Otherwise, return false
.