2

Why this code outputs 3, not 2?

var i = 1; 
i = ++i + --i; 
console.log(i);

I expected:

++i // i == 2
--i // i == 1
i = 1 + 1 // i == 2

Where I made mistake?

Sergey Metlov
  • 25,747
  • 28
  • 93
  • 153

8 Answers8

10

The changes occur in this order:

  1. Increment i (to 2)
  2. Take i for the left hand side of the addition (2)
  3. Decrement i (to 1)
  4. Take i for the right hand side of the addition (1)
  5. Perform the addition and assign to i (3)

… and seeing you attempt to do this gives me some insight in to why JSLint doesn't like ++ and --.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
3

Look at it this way

x = (something)
x = (++i) + (something)
x = (2) + (something)
x = (2) + (--i)
x = (2) + (1)

The terms are evaluated from left to right, once the first ++i is evaluated it won't be re-evaluated when you change its value with --i.

James Gaunt
  • 14,631
  • 2
  • 39
  • 57
2

Your second line is adding 2 + 1.

In order, the interpreter would execute:

++i  // i == 2
+
--i  // i == 1
i = 2 + 1
Andrew
  • 14,325
  • 4
  • 43
  • 64
0

Because you're expecting this code to work as if this is a reference object and the values aren't collected until the unary operations are complete. But in most languages an expression is evaluated first, so i returns the value of i, not i itself.

If you had ++(--i) then you'd be right.

In short, don't do this.

The result of that operation isn't defined the same in every language/compiler/interpreter. So while it results in 3 in JavaScript, it may result in 2 elsewhere.

Lee Louviere
  • 5,162
  • 30
  • 54
0

++i equals 2, `--i' equals 1. 2 + 1 = 3.

shanethehat
  • 15,460
  • 11
  • 57
  • 87
0

You're a little off on your order of operations. Here's how it goes:

  1. i is incremented by 1 (++i) resulting in a value of 2. This is stored in i.
  2. That value of two is then added to the value of (--i) which is 1. 2 + 1 = 3
ams
  • 796
  • 1
  • 12
  • 22
0

Because when you use ++i the value of i is incremented and then returned. However, if you use i++, the value of i is returned and then incremented. Reference

N0ug4t
  • 191
  • 1
  • 12
0
++$a   Increments $a by one, then returns $a.
$a++   Returns $a, then increments $a by one.
--$a   Decrements $a by one, then returns $a.
$a--   Returns $a, then decrements $a by one.
Ben
  • 355
  • 2
  • 12