0

I'm confused why I get different results when simply incrementing a variable in javascript.

First, the following obviously makes sense:

x = 0
x++
x++
// x == 2

But this doesn't make sense (not that I would actually use this in real code):

x = 0
x = x++
x = x++
// x == 0

How are these operations not practically the same? / why am I getting different final results?

bitclip
  • 187
  • 7
  • Because your setting x to itself, and then incrementing.. you maybe wanted `++x` instead. – Keith Aug 04 '20 at 15:59
  • @Keith actually its reading it into a temp, then incrementing, then assigning. – Daniel A. White Aug 04 '20 at 15:59
  • this is because [OperatorPrecedence] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) – Paritosh Mahale Aug 04 '20 at 16:03
  • @ParitoshMahale thanks. It looks like postfix increment has a higher precedence than assignment, like pretty much every other operator and whatnot. Shouldn't this mean that my x variable would be incremented then assigned to itself still? – bitclip Aug 04 '20 at 16:39
  • this means x get assign first with value 0 to new variable which is also x unfortunately. new x get's value of 0 then old x's value get increment but also get override by new x – Paritosh Mahale Aug 04 '20 at 16:48

0 Answers0