user11358047
user11358047

Reputation: 13

Javascript Do while loop stops after one iteration only

I have a do while loop that stops after one iteration only, although the condition has a false result more than once. Another thing - everything that comes after the while statement isn't executed. The code is very long so here is an example of the test condition:

do {
  let x = 0;  
  let y = 3;

  for (let j = 0; j < 9; j++) {
    if(j%2==0){
      x++;
    }
  }
} while (x < y);

Anyone knows why?

Upvotes: 1

Views: 558

Answers (2)

Ram Sankhavaram
Ram Sankhavaram

Reputation: 1228

The reason is x is not defined. let has got a block scope. and you have declared x and y in do block which doesn't have scope after the block. If you want to use them in the while condition place them either outside or change the let to var.

You are ending up with an error and hence, the code doesn't execute after the while. To sense the error surround it with a try catch.

do {
  let x = 0;
  let y = 3;
  for (let j = 0; j < 9; j++) {
    if (j % 2 == 0) {
      x++;
    }
  }
} while (x < y);

do {
  var x = 0;
  var y = 3;
  for (let j = 0; j < 9; j++) {
    if (j % 2 == 0) {
      x++;
    }
  }
} while (x < y);
console.log(x)

Hope this helps!

Upvotes: 1

DCR
DCR

Reputation: 15657

scope of x and y inside the do statement means it's not there for the while statement. But your code is looping multiple times

let x=0;  
let y=3;
do{

 
 for (let j=0; j<9; j++){
 if(j%2==0){x++;}
 console.log(x,y) 
   }
   
 }while(x<y);
 

   
do{
  let x=0;  
  let y=3;

 
 for (let j=0; j<9; j++){
 if(j%2==0){x++;}
 console.log(x,y) 
   }
   
 }while(x<y);
 

Upvotes: 1

Related Questions