3

I am fixing some code and trying to understand a certain evaluation that is happening. There was a little snippet written where 2 evaluations should happen like so :

const active = true;
const isPerson = true;
const person1Time = null;
const person2Time = null;

// this one is not working as intended
const original = !active && isPerson ? !person1Time : !person2Time;

console.log("original", original);

// fixed when second evaluation is wrapped in parens
const fix = !active && (isPerson ? !person1Time : !person2Time);

console.log("fixed", fix);

I was able to fix the code to the desired result by wrapping the ternary evaluation in parentheses. What I am wondering is - why it works like this? The !active evaluates to false, and the ternary evaluates to true, and a console.log(true && false), this evaluates to false. Perhaps I am misunderstanding something here.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
ajmajmajma
  • 13,712
  • 24
  • 79
  • 133
  • 2
    [The boolean AND has a higher operator precedence than the conditional operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) – VLAZ Dec 02 '19 at 15:35
  • 2
    It is evaluated as `(!active && isPerson) ? !person1Time : !person2Time` – slebetman Dec 02 '19 at 15:35

3 Answers3

4

Boolean operators take precedence over ternary operators. In other words, this:

!active && isPerson ? !person1Time : !person2Time;

is equivalent to this:

(!active && isPerson) ? !person1Time : !person2Time;

Therefore, you obtain a different result.

Berthur
  • 4,300
  • 2
  • 14
  • 28
3

Follow the operator precedence rules:

  • Binary AND (x && y) is priority 6.
  • Ternary (x ? y : z) is priority 4.
  • Unary NOT (!x) is priority 17.

Therfore, the NOT operator is evaluated first, then the binary AND, and lastly the ternary operator.

  • 1
    so based on what you're saying, the parenthases should look like this? `((!active) && isPerson) ? (!person1Time) : (!person2Time);` – TKoL Dec 02 '19 at 15:38
  • 1
    Yes, that's correct. All of the NOT expressions will be evaluated first, followed by the AND, and finally the ternary. –  Dec 02 '19 at 15:38
0

The original is evaluating the entire conditional expression on the left side of the ternary operator: !active && isPerson. Then based on the result of that expression - true or false - it evaluates the correct result.

Matt U
  • 4,970
  • 9
  • 28