nikoloz nikoloz - 27 days ago 8
Javascript Question

difference between a++ and ++a in while loop

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?

Answer

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