The While Loop
The while loop executes a block of code as long as a specified condition is true.
Syntax
while (condition) { // code block to be executed}
Example
In the following example, the code inside the loop runs repeatedly as long as the variable i is less than 5:
let i = 0;let text = "";while (i < 5) { text += "The number is " + i + "<br>"; i++;}
If you forget to increase the variable used in the condition, the loop will never end and can crash your browser.
The Do While Loop
The do while loop is a variant of the while loop. It executes the code block once before checking the condition, and then repeats the loop as long as the condition is true.
Syntax
do { // code block to be executed} while (condition);
Example
In the example below, the loop will execute at least once, even if the initial condition is false, because the code block is executed before the condition is tested:
let i = 0;let text = "";do { text += "The number is " + i + "<br>"; i++;} while (i < 5);
Remember to increase the variable used in the condition, or the loop will never end!
Comparing For and While
A while loop is similar to a for loop but without the initialization and increment expressions.
Example Using For Loop
This loop uses a for loop to collect the car names from the cars array:
const cars = ["BMW", "Audi", "Tesla"];let text = "";for (let i = 0; i < cars.length; i++) { text += cars[i] + " ";}
Example Using While Loop
This loop uses a while loop to collect the car names from the cars array:
const cars = ["BMW", "Audi", "Tesla"];let i = 0;let text = "";
while (i < cars.length)
{
text += cars[i] + " "; i++;
}
Both loops achieve the same result but use different looping structures.