0

I am quite confused and don't understand what's going on with the output of this javascript expression evaluation.

let m = 6;
let x=true;

m = m || x ? 10 : 0;
console.log(m); //10

In above example we have m = 6 || 10, so m should be 6 but it outputs 10.

let m = 6;
let x=false;

m = m || x ? 10 : 0;
console.log(m); //10

Similarly in above expression we have m = 6 || 0 which should also output 6 but still it outputs 10.

Can someone please explain what's going on here?

The Prenx
  • 483
  • 4
  • 15
  • ternary operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator?retiredLocale=de – bill.gates Jan 02 '23 at 16:10
  • 3
    `||` has higher [precedence](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) than `... ? ... : ...`. Your statements are evaluated as `(m || x) ? 10 : 0` – Andreas Jan 02 '23 at 16:12
  • 2
    the answer has less to do with ternary operator evaluation and more with operator precedence. I actually found the reason. The expression m || x ? 10 : 0; was being computed as (m || x) ? 10 : 0; and not as (which I wanted and was expecting) m || (x ? 10 : 0); After adding brackets it is computing correctly. – The Prenx Jan 02 '23 at 16:13

0 Answers0