Skip to content
Advertisement

What difference does it make to use the increment operator before the continue statement in a while loop? (JavaScript)

I was trying to code along a tutorial on using the “continue” statement in a while loop. In the tutorial, the code was written as shown below and it worked fine.

            ...var x = 1;
            document.write("Entering loop");

            while (x < 20) {
                x++;
                if (x == 5) {
                    continue;
                }
                
                document.write(x + "<br />");
            }
            document.write("Exiting the loop");...

but I tried it differently and it resulted to an infinite loop when I put the increment statement after the “if” block as shown below.

                ...
                var x = 1;
                document.write("Entering loop");
    
                while (x < 20) {
                    
                    if (x == 5) {
                        continue;
                    }
                    x++;
                    document.write(x + "<br />");
                }
                document.write("Exiting the loop");
               ...

I have tried to wrap my head around it but I have not been able to figure it out. Why is this so?

Advertisement

Answer

The

                if (x == 5) {
                    continue;
                }

alone means that x will never change once it reaches 5. Putting x++ before that means that x will change.

With x++ after, the loop will continue every time, infinitely.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement