what
what

Reputation: 83

Why is this while statement creating an infinite loop?

Without the if statement this loops works fine, however as soon as I add the if statement it turns it into an infinite loop-why? From my understanding continue should make the loop skip an iteration and then run as normal?

 let num=0;
 while(num<10){
        if(num===4){console.log("skipping "+num);
                continue;
    }
     console.log(num++);
}

Upvotes: 0

Views: 69

Answers (2)

Rohit Agrawal
Rohit Agrawal

Reputation: 1521

Inside your while loop when num gets incremented to 4, it enters the if block and you are not incrementing num inside if block.

Also you are using continue which skips the code in the current iteration and moves to the next iteration. This keeps on happening and num is never incremented which leads to an infinite loop.

The following code prints numbers from 0 to 9 skipping 4 as asked in the question.

let num = 0;

while(num < 10) {

    if(num === 4) { 
        console.log("skipping " + num++);
        continue;
    }

    console.log(num++);
}

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68635

You need also to increment the num in the if block. Without it after the if statement it never reaches to the num++ and you never change the value of num, so it stays 4 and every time goes into the if. You can add ++ in the if statement.

let num = 0;

while(num < 10) {
    
    if(++num === 4) { 
        console.log("skipping " + num);
        continue;
    }
    
    console.log(num);
}

Upvotes: 2

Related Questions