May 06, 2021 JavaScript
The purpose of the JavaScript while loop is to execute statements or blocks of code over and over again.
Loops can execute blocks of code all the time as long as the specified condition is true.
The while loop loops through blocks of code when the specified condition is true.
The loop in this example will continue to run as long as the variable i is less than 5:
Tip: In the JavaScript programming practice section of this site, you can do iterations using while statement loops with practice.
If you forget to increase the value of the variable used in the condition, the loop never ends. This may cause the browser to crash. |
The do/while loop is a variant of the while loop. The loop executes a block of code once before checking that the condition is true, and then repeats if the condition is true.
The following example uses a do/while loop. The loop is executed at least once, even if the condition is false, because the block of code executes before the condition is tested:
Don't forget to increase the value of the variable used in the condition, or the loop will never end!
If you've read the previous chapter about for loops, you'll find that the while loop looks a lot like the for loop.
The loop in this example uses the for loop to display all the values in the cars array:
The loop in this example uses the while loop to display all the values in the cars array: