When running the following code on the console:
var counter=0; while(counter<5){ console.log(counter); counter++; }
console o \ p: 0 1 2 3 4 4
whereas for the following code it works fine, without repeating the last value:
for(var i=0; i<5; i++){ console.log(i); }
console o \ p: 0 1 2 3 4
Now, if I set higher for the loop after the above while loop, the output will be fine:
var counter=0; while(counter<5){ console.log(counter); counter++; } for(var i=0; i<5; i++){ console.log(i); }
console o \ p: 0 1 2 3 4 0 1 2 3 4
whereas if I put a while loop after the loop, a repetition of the last number will be found.
for(var i=0; i<5; i++){ console.log(i); } var counter=0;while(counter<5){ console.log(counter); counter++; }
console o \ p: 0 1 2 3 4 0 1 2 3 4 4
Request everything to indicate the reason for this unexpected while loop behavior. Thanks.
javascript for-loop while-loop
Sarge
source share