0

[JS] Why this output?

This is the code of a challenge: for(i=0;i<3;i++) document.write(i); for(i=0;i<3;++i) document.write(i); It outputs "012012", but why? The first for-loop is obvious. I don't get the second one. Since there is a pre-increment, that means first i is incremented and then the argument is evaluated, the loop should skip 0, because i gets the value 1 at the first increment. Hence the output should be "01212". What am I getting wrong? Could someone explain this, please. Thanks in advance.

8th Jul 2017, 10:44 PM
Pete Wright
Pete Wright - avatar
4 ответов
+ 12
The way a for works, it initializes the counter, checks the condition(s), runs the statements, and then increments the counter. It doesn't matter whether you use pre or post, it all still works in the same order. Or, look at it this way. This while behaves exactly the same as those fors: var i = 0; while(i < 3) { document.write(i); i++; //++i; } Either way, the ++ is its own separate statement. All pre and post do is determine where the increment happens in order of operations. And since there are no other operations, pre and post work the same here.
8th Jul 2017, 10:57 PM
Tamra
Tamra - avatar
+ 5
The increment is ran after the loop is finished and before the condition is evaluated. So there's nothing making i++ different from ++i. "that means first i is incremented then evaluted". But the condition isn't evaluated at the same time. The increment of a for loop comes before the condition (with the exception of the first run). In order for what you thought to be true, the code would need to look like: for(i = 0; ++i < 3;)
8th Jul 2017, 10:57 PM
Rrestoring faith
Rrestoring faith - avatar
+ 5
Because the condition to terminate the loop (if i == 3 in this case) is checked before the pre increment is evaluated, so in effect ++i is calculated after the loop continues. You could replace the for loop with a while loop to get a clearer picture. For example, this would give a different result. var i=0; var j=i; while(j<3) { document.write(i); j = ++i; } or var i=0; var j=i; while(j<3) { document.write(i); j = i++; }
8th Jul 2017, 10:58 PM
Karl T.
Karl T. - avatar
+ 1
the code outputs 012012 cos the first evaluates differently while the second one also does the same since there's no connection between the two
8th Jul 2017, 11:02 PM
Nomeh Uchenna Gabriel
Nomeh Uchenna Gabriel - avatar