|| and ?? 03

|| (OR)

The “OR” operator is represented with two vertical line symbols:

result = a || b;

In classical programming, the logical OR is meant to manipulate boolean values only. If any of its arguments are true, it returns true, otherwise it returns false.

Nullish coalescing operator '??'

The nullish coalescing operator is written as two question marks ??.

As it treats null and undefined similarly, we’ll use a special term here, in this article. For brevity, we’ll say that a value is “defined” when it’s neither null nor undefined.

The result of a ?? b is:

  • if a is defined, then a,
  • if a isn’t defined, then b.
result = (a !== null && a !== undefined) ? a : b;
|| and ?? 02

You have probably used these two expressions in Javascript, let’s examine the next snippet.

|| and ?? 04

As you can see, the result string is joe - because lastname is null, so the expression || checks for null and undefined values, in this case the expression chooses the second value - as result.

Now, if for some reason you declare the initial value of lastname as an empty string, you’ll get the same result: joe - , that’s because for || , the empty string is a valid data, let’s go further and declare the initial value as zero 0 , surprise! you got the same result joe -

So, now it’s time to test the ?? expression, let’s see the next code:

|| and ?? 05

As you can see, even though i declared the initial value of lastname as an empty string, you get joe , and of course if you change the value as zero, you also get the same result.

To wrap it up, you must to know that ?? is more permissive that || , so in case you want to catch empty strings or 0 values, the || is the way to go, else ?? is pretty sufficient for you, it’s up to the requirement.

|| and ?? 06