-2

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?

Anamaria Miehs
  • 521
  • 1
  • 4
  • 10
  • 1
    `v === null || v`…? (If *truthy* is desired, else `... v === true`.) – deceze Aug 16 '21 at 08:40
  • 2
    If your nullableBool can only ever be true, false or null, then `v !== false` would do it. Otherwise `v === null || v === true` or `[null, true].includes(v)` – CherryDT Aug 16 '21 at 08:41
  • 2
    Another way (checking for truthyness and handling undefined like null though) would be `v ?? true` – CherryDT Aug 16 '21 at 08:43
  • @CherryDT Make that an answer and earn some quick votes :-) – Bergi Aug 16 '21 at 08:46
  • I always feel like one-liners I wrote on the go aren't "ripe" for an answer where I'd like to link docs, show example inputs and outputs and stuff. Feel free to edit it into your own answer. – CherryDT Aug 16 '21 at 08:48

2 Answers2

5

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

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.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231