In Javascript While, the loop repeats the last number when counting from 1 to 5 when running on the console

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.

+7
javascript for-loop while-loop
source share
2 answers

When performing operations, the console always displays the return value of the last line executed.

It means just writing

 var counter = 0; ++counter; 

write 1 to the console.

The same thing happens in your loop, the return value of the last counter++ is displayed on the console as the value of the last executed expression.

+9
source share

The result of the logging method depends on the JavaScript engine in the browser. The last printed value is not inferred from the loop itself.

Try: var counter = 0; while (counter <5) {console.log (counter ++); }

+2
source share

All Articles