0

So the double pipe || is the logical OR operator.

I want to create a function where it can be either foo, or when thats flase (or falsy?) then it should use a default fallback. In this case 'bar'.

const foo = 0;
const bar = 'somethingElse';

const qux = foo || bar;

console.log(qux); // returns 'somethingElse'

Now the above example will work unless foo is 0. Since JS will interpret that als falsy.

Now the following seems to be working:

// ...
const qux = typeof foo !== 'undefined' ? foo : bar;

But I'm wondering if there is a better solution. What would be the best way of handling such a scenario?

Remi
  • 4,663
  • 11
  • 49
  • 84
  • `typeof foo !== 'undefined'` is perfectly fine. You can use a helper function if you find yourself doing this often. `function def (l, r) {return typeof l=='undefined'?l:r}` – Moritz Roessler Jun 23 '20 at 12:13

2 Answers2

3

Yes, || checks for the first operand to be falsy (false when coerced to a boolean), and 0 is exactly that.

If you want to check for null and undefined only, you can use the nullish-coalescing operator:

const qux = foo ?? bar;

If you want to check for exactly undefined, you should use the conditional operator as you did.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Awesome! I didn't know about this operator yet, but it's exactly what you need in a lot of situations. – mcv Jun 23 '20 at 12:22
0

Since the issue is only if foo is 0. So you can modify the condition like this. This will work for everything as expected.

const qux3 = ((foo === 0 && foo) || foo) || bar;