-1

This JavaScript code will result in -11, but I don't know what is the mathematical process.

let x = 2;
let y = 4;
console.log(x -= y += 9)
Spectric
  • 30,714
  • 6
  • 20
  • 43
  • 7
    I would reject any pull request that had code like that. While it is possible this could be concretely explained, the amount of time for someone to look at that code and understand what it is doing is prohibitive and there is likely a much better solution for arriving at the desired result. – crashmstr Apr 28 '21 at 15:48
  • 1
    This certainly feels like a homework/interview question that's the sort of code you will (hopefully) never actually run into. – DBS Apr 28 '21 at 15:49
  • 2 - (4 + 9) ... – Jonas Wilms Apr 28 '21 at 15:49
  • This is a weird piece of code, but the evaluation process, I'm fairly sure, is `x -= (y += 9)`, which means 1. add 9 to y, so y = 13. Then 2. subtract y from x, so x -= 13 or x = x - 13 = 2- 13 = -11 – Zorobay Apr 28 '21 at 15:51
  • 2
    Just because you can, does not mean you should – Liam Apr 28 '21 at 15:51
  • 1
    [Subtraction assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Subtraction_assignment), [Addition assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Addition_assignment) – Spectric Apr 28 '21 at 15:52
  • An understanding of [operator precedence](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) would also aid your understanding. – ADyson Apr 28 '21 at 15:54

3 Answers3

2

Break down each step:

y += 9 
y = y + 9
y = 4 + 9
y = 13
x -= y
x = x - y
x = 2 - 13
x = -11
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
2

It might be helpful to think of this as

let x = 2;
let y = 4;
let z = x -= (y += 9);
console.log(z);

We're setting the term in the parantheses to y += 9 (which is 13), then setting z to x -= 13, which is -11.

That being said, this is a horrible way of writing this!

Seth Lutske
  • 9,154
  • 5
  • 29
  • 78
0

The execution start with y=y+9 which is 4+9=13 then it evaluates x=x-y which is 2-13=-11 so answer is -11.