-2

i have got this code:

 function isTruthy(value) {
    switch (value) {
      case false:
        return false;
      case null:
        return null;
      case undefined:
        return undefined;
      case 0:
        return 0;
    }
    return value
  }


 const nextValue = isTruthy(xsd[nextPath]) || isTruthy(xsd`xd:${[nextPath]}`) ;
 

if the first part isTruthy(xsd[nextPath]) is 0 but the second part isTruthy(xsd`xd${[nextPath]}`) is undefined then the nextValue value will be undefined, but i would like if it would be 0, how can i do that ?

2 Answers2

1

Try the nullish coalesing operator. Its almost the same like the logical or || with the difference that it operates the right side if the left side is an nullish value.

Nullish values are: null, undefined

Since 0 is falsy but not nullish it will execute the left side.

 const nextValue = isTruthy(xsd[nextPath]) ?? isTruthy(xsd`xd:${[nextPath]}`) ;
bill.gates
  • 14,145
  • 3
  • 19
  • 47
  • Thank you @Ifaruki but, what happening if i need to test more than two statement ? Like a || b || c.. and if one of them is 0 but another ones are undefined i need to get the 0 – mynameiszsofia Sep 16 '20 at 13:30
  • @mynameiszsofia replace `||` with `??` – bill.gates Sep 16 '20 at 13:30
  • @mynameiszsofia `a ?? b ?? c` will return `0` if any of these is zero and the others are `null` or `undefined`. – VLAZ Sep 16 '20 at 13:31
  • @mynameiszsofia also this functions does not make sense to me like in case `false` return `false` why dont you just direclty return `false`? same for the other values too. is this an minified version of your function? – bill.gates Sep 16 '20 at 13:32
  • @Ifaruki yes its a minified version, and this nullish thing is not the best way for the problem solving for me, because if all of the value is undefined this statement will be zero instead of undefined – mynameiszsofia Sep 16 '20 at 13:36
0

An alternative to the coalesce operator (Ifaruki's answer) is just adding another 'or zero' to the end of your line. undefined is false-ish, so it will pass though to the final 'or' argument.

const nextValue = isTruthy(xsd[nextPath]) || isTruthy(xsd`xd:${[nextPath]}`) || 0;
Devin Burke
  • 13,642
  • 12
  • 55
  • 82