The while loop executes a block of code continuously as long as a given condition remains true.
| while (condition) { // code block to be executed } |
In the following example, the loop will repeatedly execute the code as long as the variable (i) is less than 10.
| while (i < 10) { text += “The number is “ + i; i++; } |
| If you forget to increment the variable used in the condition, the loop will run indefinitely, potentially crashing your browser. |
The do-while loop is a variation of the while loop. It executes the code block once before checking the condition, and then continues to repeat the loop as long as the condition remains true.
| do { // code block to be executed } while (condition); |
The example below demonstrates a do-while loop, which ensures that the code block runs at least once, even if the condition is false, since the condition is checked only after the code block is executed.
| do { text += “The number is “ + i; i++; } while (i < 10); |
Make sure to increment the variable used in the condition; otherwise, the loop will run indefinitely!
If you’ve read the previous chapter on the for loop, you’ll notice that a while loop is quite similar, with the first and third statements omitted.
The loop in this example utilizes a for loop to gather the car names from the cars array.
| const cars = [“BMW”, “Volvo”, “Saab”, “Ford”]; let i = 0; let text = “”; for (;cars[i];) { text += cars[i]; i++; } |
This example features a while loop that retrieves the car names from the cars array.
| const cars = [“BMW”, “Volvo”, “Saab”, “Ford”]; let i = 0; let text = “”; while (cars[i]) { text += cars[i]; i++; } |