Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding JavaScript evaluation [duplicate]

Tags:

javascript

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.

like image 416
ajmajmajma Avatar asked Sep 26 '26 11:09

ajmajmajma


2 Answers

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.

like image 136
Berthur Avatar answered Sep 29 '26 19:09

Berthur


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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!