Why does the do, while loop display the last number twice?

241 Views Asked by At

I have the following code:

 var a = 0;
    
    do {
      console.log(a);
      a++;
    } while (a < 10);

And I was playing around with it to gain a better understanding of what is going on and I noticed that this will write the final number 9 twice. Can anyone explain this to me please?

Much appreciated.

1

There are 1 best solutions below

3
On BEST ANSWER

its working perfectly fine , the result is also perfect . the last number you see is because of "the console also displays the value of the last expression executed in the code you run there." And this is something that expression returns . if some how there is a break statement in the loop the return will be undefined. and you will see only the console value .

or if you put the entire exp in a function you will not see this return . because the function will not return any thing like-

if you wanna check properly try using this

var fun=function(){var a = 0;

do {
  console.log(a);
  a++;
} while (a < 10);}
fun()