1
payload = {type: 3}
const type = payload.type || state.active === "period" ? 1 : 2;
// type returns 1

I'm surprised by the return of type which is 1.. I was expecting it to be 3.. What happened here? What I want to really achieve is if the type index is not available then state.active === "period" ? 1 : 2 will be the basis of the value of type..

How to achieve this in a clean one line?

Dean Christian Armada
  • 6,724
  • 9
  • 67
  • 116
  • 1
    ...[order of precedence](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence). Yet again. – VLAZ Feb 05 '20 at 11:08
  • Not really but the answer above is perfect for me – Dean Christian Armada Feb 05 '20 at 11:18
  • 1
    The question is *exactly the same* - there is an OR and a conditional operator used in the same expression. Which is what you have - an OR and a conditional operator in the same expression. I fail to see how the other question differs from this one. – VLAZ Feb 05 '20 at 11:20

1 Answers1

4

You need parentheses, because of the operator precedence.

const type = payload.type || (state.active === "period" ? 1 : 2);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392