-3

Please read whole topic, before post answer. No answer found to this question in post: ++someVariable Vs. someVariable++ in Javascript

var i = 1;
i = i++ * 2; // i = 2, .. why not 4 ?

interpreter does the multiply (1*2), but where is the increment ( i++ )?

var i = 1;
i = ++1 * 2; // i = 4 

I'm understand, that the i++ does the increment after the statement, ++i does it before the statement, but in this example: i = i++ * 2 // (1*2), how the interpreter works?, where is the increment of i in this case? maybe i = (1*2)+1 )), or i = (1*2) and no more i exist, and nothing to increment??

HOW ?

P.S. I think, it is a wrong question, but as Brooks Hanes said(in comment), this is a learning example.

Geseth
  • 3
  • 5
Pavel Zheliba
  • 89
  • 1
  • 6
  • 2
    i++ does the increment after the statement, ++i does it before the statement – Patrick Evans Feb 12 '15 at 17:49
  • It's no just JavaScript, increment operator works in many (most if not all) languages like this – gskema Feb 12 '15 at 17:49
  • This question is a good example of writing code in such a way that is not instantly understandable. I know this is probably a learning example, but many, many mistakes have been made from trying to save a line of computation. – Brooks Hanes Feb 12 '15 at 17:50
  • 1
    Does it really even matter: i = (i + 1) *2; seems just as easy. – David P Feb 12 '15 at 17:51
  • But you are assigning the whole thing to i. So I will get updated correctly in the end. Now I could see if you wanted to j = ++i * 2; – David P Feb 12 '15 at 18:03
  • I think, it is a wrong question.. sorry. As Brooks Hanes said, this is a learning example. I'm understand, that the i++ does the increment after the statement, ++i does it before the statement, but in example: i = i++ * 2 // (1*2), how the interpreter works?, where is the increment of i in this case? maybe i = (1*2)+1 )), or i = (1*2) and no more i exist, and nothing to increment?? – Pavel Zheliba Feb 12 '15 at 19:05

2 Answers2

10

i++ means: read the value of variable i, then increase variable i

++i means: increase variable i, then read the value of variable i

Mex
  • 1,011
  • 7
  • 16
0

This is an interesting little problem, a simple experiment shows what is happening. jsFiddle

var i = 3; p = i++ *2; console.log(i, p);

The 2 is multiplied by i (3) the result (6) is placed in p. Then a copy of the original value of i (3) is incremented and placed back in i. This behaviour is logically consistent with the following:

var i = 3; var p = 0; function adder(x) { p = x + 2; }; adder(i++); console.log(i, p);

This makes a strange kind of sense because the post increment is supposed to happen after the statement.