"A Website"

Designed by Christian Gundersen

A Brief Overview of Looping in JavaScript

Looping is a powerful tool that is used to control how many times a block of code will execute. There are two main variants of loops; the while loop and the for loop.

While Loops

                

While loops will execute until a boolean expression determined by the programmer is no longer true. Below I will provide a basic example of the structure of a while loop:

                    let x = 1;
                    while(x <= 10){
                        console.log("This is iteration number " + x);
                        x ++;
                    }
                

The while loop example above will log the value of x until x is greater than 10, as specified by the boolean statement "x <= 10" following the while keyword. Every time the block of code executes, the x value will increase by one as specified by the "++" incrementor. Therefore, this loop will log the values 1 through 10 and then terminate the loop.

For Loops

                

For loops are slightly different from while loops because they have a counter variable included in the syntax of the for statement. The example below will show a for loop that will give the same result as the while loop example above. This way you will be able to see the difference in syntax between the two loops even though they will give the same result.

                    for(let x=1; x<= 10; x++){
                        console.log("This is iteration number " + x);
                    }  
                

The two examples of code I have provided above will give the same output, but it should be apparent how they set up differently and how they could have different use-cases. It is notable that the counter variable is included in the syntax of a for loop, whereas if a counter variable is required in a while loop, it must be initiated outside of the while loop's boolean statement.