0
var a = 0;
(++a)+(a++)+(++a); 
print(a);

This prints 3. I'm assuming it only executes single increment.

var a = 0;
(++a)+(a++)+(--a); 

This prints 1. What's the rule to follow here?

Thank you.

mikbal
  • 1,168
  • 1
  • 16
  • 27
  • Here. read the difference between i++ and ++i http://stackoverflow.com/questions/484462/difference-between-i-and-i-in-a-loop – Kai Qing May 04 '13 at 00:50
  • I'm sure you're just curious (I am, for the answer), but is there a reason you're doing this? I mean, why can't you increment the number as you want *before* you add them up? – Ian May 04 '13 at 00:51
  • Yes, it's mainly curiosity. I am also developing a scripting DSL. That's why i would like to know how a common language like javascript implements these. – mikbal May 04 '13 at 00:52
  • 1
    Don't write code like that. – David G May 04 '13 at 00:53

2 Answers2

6

You're not assigning the outcome of your addition to anything. You do this:

(++a)+(a++)+(++a); 

Which increments a 3 times. 0 + 3 = 3 so a is the value 3.

James Montagne
  • 77,516
  • 14
  • 110
  • 130
1

JavaScript is executed left-to-right. You can see this by seeing what happens when you use multiplication

a = 1;
   ++a *   a; // 4
//   2 *   2  =  4

a = 1;
     a * ++a; // 2
//   1 *   2  =  2

a = 1;
   a++ * a  ; // 2
// 1   * 2    =  2

a = 1;
   a   * a++; // 1
// 1   * 1    =  1

After each of these, the resulting a is 2.

Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • Thank you. Then b = (++a)+(a++)+(++a); is b = 1 + 1 + 3. b is 5, a is 3. Looking at the statement i would think it is 6. Like this: a+=1; a+=1; b=a+a+a; a+=1; I gotta learn to think like javascript. Thank you. – mikbal May 04 '13 at 01:39