JavaScript While Loops
- Previous Page JS Loop For Of
- Next Page JS Break
The loop will keep executing the code block as long as the condition is true.
While Loop
The while loop will keep looping the code block as long as the specified condition is true.
Syntax
while (Condition) { The code block to be executed }
Example
In the following example, the code in the loop will run over and over again 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 never end. This can cause the browser to crash.
Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once before checking if the condition is true, and then will repeat the loop as long as the condition is true.
Syntax
do { The code block to be executed } while (Condition);
Example
The following example uses a do/while loop. This loop will execute at least once, even if the condition is false, because the code block is executed before the condition is tested:
do { text += "The number is " + i; i++; } while (i < 10);
while (i < 10);
Do not forget to increment the variables used in the condition, otherwise the loop will never end!
Comparison of For and While
The loop in this example uses If you have already read the previous chapters about loops, you will find that the while loop is quite similar to the for loop, where statements 1 and 2 can be omitted.To extract the car brands from the cars array:
Example
var cars = ["BMW", "Volvo", "Saab", "Ford"]; var i = 0; var text = ""; For Loop text += cars[i] + "<br>"; i++; }
The loop in this example uses While LoopTo extract the car brands from the cars array:
Example
var cars = ["BMW", "Volvo", "Saab", "Ford"]; var i = 0; var text = ""; while (cars[i]) { text += cars[i] + "<br>"; i++; }
Textbook
For more information about JavaScript while statementFor more information on the knowledge, please read the relevant content in the Advanced JavaScript Tutorial:
- ECMAScript Iteration Statements
- Iteration statements, also known as loop statements. This section introduces the four iteration statements provided by ECMAScript.
- Previous Page JS Loop For Of
- Next Page JS Break