desh
desh

Reputation: 689

Confused about do while loop in javascript

According to MDN, do while loop states that this is the syntax and do runs once despite the condition

do statement while (condition);

The following is my code

let mergeArr3 = (arr1 , arr2) => {
   let i = 1;
   do {
      console.log('hello') //prints hello 5 times
      i++;
   }
   while (i < 6 ) {
      console.log(i) //prints 6
      console.log('world') // prints world once
   }
   
}

mergeArr3(arr1 , arr2)

I am struggling to understand two things:

  1. Why does console.log(i) print 6 when 6 < 6 suppose to be evaluated to false and it shouldn't be running that line of code when i === 6.

  2. Do is suppose to run once, but why is it running 5 times?

Upvotes: 0

Views: 309

Answers (2)

Pac0
Pac0

Reputation: 23149

the "loop" part is only the block between do and while.

It's executed at least once, and until the while condition is falsy

The block you wrote after the while is just an independent block of code, that should be read like this for better clarity :

   let i = 1;

   // loop do -- while
   do {
      console.log('hello') //prints hello 5 times
      i++;
   }
   while (i < 6) // if the condition here is true, execute the above block again.

   // this is just a legal block of code but completely unrelated to the loop.
   {
      console.log(i) //prints 6
      console.log('world') // prints world once
   }

So, the last block after the loop is executed when i is not less than 6, i.e. when i is exactly 6. This explains the output.

Upvotes: 4

Piyush Rana
Piyush Rana

Reputation: 667

 while (i < 6 )
       {
          console.log(i) //prints 6
          console.log('world') // prints world once
       }

The part after while condition is never the part of do-while its just normal block with console inside. This will always be interpretes like below by JS or any language that supports do-while:

let mergeArr3 = (arr1 , arr2) => {
   let i = 1;
   do {
      console.log('hello') //prints hello 5 times
      i++;
   }
   while (i < 6 );
       {
          console.log(i) //prints 6
          console.log('world') // prints world once
       }
       
    }

Upvotes: 0

Related Questions