-3

i am trying to figure out, why do i end up with different outcome, when i use a++ versus ++a in a while loop? i know that they are postfix and prefix operations but still do not get why i am getting the results i get

var a = 1;
 while (a < 3) {  
   console.log(a); 
   a++;

}

i ger results: 1, 2, 2 , when using ++a instead of a++ i get different outcome.

 var a = 1;
 while (a < 3) {  
       console.log(a); 
       ++a;
  }

in this case i get 1,2,3. can someone explain operations order step by step and why do i get the output i get?

nikoloz
  • 67
  • 7
  • 3
    Possible duplicate of [Why doesn't the shorthand arithmetic operator ++ after the variable name return 2 in the following statement?](http://stackoverflow.com/questions/11218299/why-doesnt-the-shorthand-arithmetic-operator-after-the-variable-name-return) or of http://stackoverflow.com/questions/1546981/post-increment-vs-pre-increment-javascript-optimization/25056276#25056276 – Teemu Nov 11 '16 at 05:02
  • 1
    you'll only get 1,2,2 or 1,2,3 if you run this in the console - outside the console both will only output 1,2 - check the console when running this [fiddle](https://jsfiddle.net/26jsvx62/) – Jaromanda X Nov 11 '16 at 05:08
  • 1
    the last number you see in the console is the "result" of the last operation ... so, 2 (because of post increment) in the first case, and 3 (because of pre increment) in the second - if you add ONE line after the `}` with just `a;` - both will show 1,2,3 – Jaromanda X Nov 11 '16 at 05:13
  • @JaromandaX thanks, now i get it. how do i mark your comment ar right answer? thanks for your time. – nikoloz Nov 11 '16 at 05:29
  • It's not an answer so you can't :p – Jaromanda X Nov 11 '16 at 05:30
  • Added as an answer with more explaining – Jaromanda X Nov 11 '16 at 05:33

1 Answers1

1

You'll only get 1,2,2 or 1,2,3 if you run this in the console - outside the console both will only output 1,2 - check the console when running this fiddle

When running in the console, the last number you see in the console is the "result" of the last operation ... so, 2 (because of post increment) in the first case, and 3 (because of pre increment) in the second -

if you add ONE line after the } with just a; - both will show 1,2,3 - like so

var a = 1;
 while (a < 3) {  
   console.log(a); 
   a++;
}
a;

and

var a = 1;
while (a < 3) {  
    console.log(a); 
    ++a;
}
a;

shows that a is the same after the while loop finishes

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87