View Full Version : JavaScript evaluation order

03-31-2003, 06:53 AM
Hmm, anyone know of where you can get any information about exactly what JavaScript does and on what order, before assignment? JavaScript seems to be different from many other languages on this small script:

var i=1;
i+=i++ + ++i; // Gives i==5
// 1+(1 + 3)=5
// i 1 2 3
Indicating an order of the following:
1. Lhs snapshot when i==1
2. Rhs eval of i++ gives 1, i==2
3. Rhs eval of ++i gives 3, i==3
4. Rhs eval of 1+3 gives 4, i==3
5. Eval of the assignment i+=4 from snapshot gives i==5.

However, many other languages give 6,7 or even 8. Why doesn't JavaScript?

This order is the same for the reverse:
var j=10;
j-=j-- - --j; // Gives j==8
// 10-(10 - 8)=8
// j 10 9 8
1. Lhs snapshot when j==10
2. Rhs eval of j-- gives 10, j==9
3. Rhs eval of --j gives 8, j==8
4. Rhs eval of 10-8 gives 2, j==8
5. Eval of the assignment j-=2 from snapshot gives j==8.

My guess, is that the first thing JavaScript does is rewrite i+= into i=i+. Then, the evaluation of rhs goes ltr. Other languages evaluate rhs first, then do i=i+rhs, thus evaluating to 7. Those evaluating to 6 must be doing the incrementation from i++ after the entire expression has been evaluated. I can't think of a reason why it would eval to 8 in any language, but that is the case. Oh, well.