Thursday, July 4, 2019

|| operator, a coalesce like in Javascript

When I first encounter coalesce in SQL, I was amazed by the simplicity and the usefullness of the function. So I searched for it in other languages.

The closest I get in Javascript was to use the || operator. Using it on multiple operand will result in taking the first non null, non undefined, non false variable. See done below:

const a = null;
const b = false;
const c = 8;

a || b || c;
8

const d = true;

a || d || c;
true

const e = undefined;

a || e || c;
8

3 comments:

  1. In python we can use or

    a=None
    b=False
    c=8
    a or b or c gives 8

    ReplyDelete
  2. In Java I would go with Stream.of(...).filter(...).findFirst()...
    Or apparently there is a method firstNonNull in Apache Commons Lang 3 but it is only for null check

    ReplyDelete