megamonium
megamonium

Reputation: 483

Javascript operator precedence question: i = i— + ++i

Please consider this snippet of code:

var i = 1;
i = i-- + ++i;

My understanding of the order in which the operators & operands are processed is as follows:

  1. i is incremented by 1 (pre-fix increment)
  2. i is added to i( addition )
  3. i is decremented by 1(post-fix decrement)
  4. The value of the right hand side is assigned to i (assignment operation)

If my understanding is correct, i should end up having a value of 3. However, I printed out the result using some online javascript interpreter, and the end value of i is 2.

Where did I get wrong?

Upvotes: 0

Views: 97

Answers (3)

Santa
Santa

Reputation: 377

Understanding the logic with precedence values:

var i = 1;
i = i-- + ++i;

prefix increment(++i) precedence  = 17
postfix decrement(i--) precedence = 16

addition(+) precedence = 14

i = 1 + 1
i = 2

More precedence related info can be found in, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

Upvotes: 0

moficodes
moficodes

Reputation: 869

var i = 1;
i = i-- + ++i;

this is how the compiler will go about working through this code

  1. create a variable called i
  2. set the value of i to 1
  3. (rhs first element) take value of i (1) decrement value (i is now 0)
  4. (rhs second element) increment value of i (i is now 1)
  5. set the value of i to rhs (2)

Upvotes: 2

Freyja
Freyja

Reputation: 40804

JavaScript always evaluates subexpressions in a left-to-right order, and then applies the operator:

// parentheses added for clarity
i = (i--) + (++i); // i = 1

i =   1   + (++i); // i = 0 after i--

i =   1   +   1  ; // i = 1 after ++i

i =       2      ;

Upvotes: 2

Related Questions