While & Do/While Loops

While Loop

Probably the simplest loop structure, this code block will run if and only if the condition is true. Once it becomes false, the loop stops. You can also break out of the loop with a break; statement. Keep in mind that the while loop may not run at all, depending on the condition.

Syntax

The syntax of a While loop is some of the simplest possible:

while (someCondition) {
// Do anything in here
}

Example 1 - Infinite Loop

// This will loop forever (infinite loop)
// unless you call 'break;' somewhere inside the loop block
// Infinite loops are VERY bad as you have no ability to properly end it
while (true) {
console.log("INFINITE LOOP!");
}

Example 2 - Until a Value

Clicking the blue "Powered By" button will open this example in a new tab

Do While Loop

The Do While is a variation on the While. It is guaranteed to run at least once but it will only loop back to the top if the condition is true.

Syntax

The syntax is similar to the While loop but notice the differences - especially the semicolon ending the statement.

do {
// Some code that is guaranteed to run once
} while (someCondition);
/*** Note that there is a semicolon at the end of the statement. ***/

Example 3 - Not Zero

// Add numbers the user enters until they enter zero
// Assuming good input from the user
let userNumber, sum = 0;
// loop body is executed at least once
do {
userNumber = Number(prompt("Please enter a number:"));
sum += userNumber;
} while (userNumber !== 0);
console.log("Total sum was %i", sum);
// You might not recognize the console.log on line 12. That is a different
// way of including a variable into a string (it only works in console.log).

Example 4 - Print a Box

Clicking the blue "Powered By" button will open this example in a new tab