chessplayer
chessplayer

Reputation: 41

Operator Precedence using double brackets in JS

I got this code:

let x = -2;
let ex = ((x += 10) > ++x) * 2;
console.log(ex);

Trying to figure out why the output in the console here is 0, while I think it should be 2? Here's my reasoning behind it:

When I reference the order of precedence in MDN, I also need to account for double brackets here. This means this is how I prioritized my actions:

  1. += (in double brackets) // I get a value 8
  2. ++ (according to the second highest priority in a global bracket) // I get -1
  3. > (the third priority) // at this point I'm comparing 8 against -1 (8 > -1) = true, meaning the value now becomes 1
  4. * (last one) // 1 * 2 = 2

Above is my own thought process. Can you please explain why I should get 0 in the end? Intuitively, it means the boolean value in brackets needs to be false, to be converted to 0. And then 0 * 2 = 0.

Thanks.

Upvotes: 1

Views: 138

Answers (1)

Kelvin Schoofs
Kelvin Schoofs

Reputation: 8718

It makes sense if you look at it one expression at a time:

let x = -2;
// x = -2

let ex = (
  ( x+= 10)
  // x = 8 (which is what this expression returns)
  >
  ++x
  // x = 9 (which is what this expression returns)
) * 2:

// In other words:
let ex = (8 > 9) * 2;
// which results in 0

Operator precedence matters, yes, but that doesn't mean the VM will suddenly pre-calculate an expression on the right-hand side of >. When evaluating binary operator expressions, it will always evaluate the left-hand side, then the right-hand side. (with the exception of e.g. && where the right-hand side might be skipped).

Upvotes: 1

Related Questions