Simone
Simone

Reputation: 21272

Why i += i + i++ equals 0?

Consider this code:

var i = 0;
>> undefined

i += i + i++;
>> 0

i
>> 0  // why not 1?

I would expect i to be 1 because of the increment (++) operator. What I think should happen is something like:

i = 0 + 0 + (i = i + 1)
i = 0 + 1
i = 1

Why it's returning zero instead? Could someone explain what happens under the scene?

Upvotes: 2

Views: 214

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149040

It's important to realize is that i++ increments i, but returns the original value of i. This postfix version of the operator (also called post-increment) is documented here:

If used postfix, with operator after operand (for example, x++), then it returns the value before incrementing.

So this evaluates to:

i = 0 + (j = i, i += 1, j);

Note the use of the comma operator above.

What you're describing is much more like the prefix version of the operator (also called pre-increment), ++i, which would evaluate to:

i = 0 + (i += 1);

And which does indeed return 1.

Upvotes: 5

davide
davide

Reputation: 316

It should be

i += i + (++i);

If you use i++ the increment is after the expression, so it will resolve simply as i

Upvotes: 2

Related Questions