Program Flow: Loops

Learn how to use loops for repetitive execution of selective code based on conditions or iterations.

Loops are another fundamental building block that allow us to run a procedure repeatedly. In this lesson, we will take a look at while and for loops.

while loops

To run a segment of code while a certain condition remains true, use a while loop.

Press + to interact
var num = 0;
while(num <= 10) {
if(num !== 10) {
console.log("The number is", num, "- less than 10");
} else {
console.log("The number is", num, "- the loop is now over");
}
num++;
}

In the while statement, if the given condition is true, the code block will execute. Once the program has been executed, it will go back to the beginning of the while statement and check if the condition is still true. If it is, the code will once again execute. This will continue happening (the execution of the code block loops) up until the while statement’s condition becomes false. ...