JavaScript Statements Reference
Loop through a block of code as long as a variable (i) is less than 5:
The result of text will be:
More "Try it Yourself" examples below.
The while statement creates a loop that is executed while a specified condition is true.
The loop will continue to run as long as the condition is true. It will only stop when the condition becomes false.
JavaScript supports different kinds of loops:
Tip: Use the break statement to break out of a loop, and the continue statement to skip a value in the loop.
Statement | |||||
---|---|---|---|---|---|
while | Yes | Yes | Yes | Yes | Yes |
Parameter | Description |
---|---|
condition | Required. Defines the condition for running the loop (the code block).
If it returns true, the loop will start over again, if it returns false, the
loop will end. Note: If the condition is always true, the loop will never end. This will crash your browser. Note: If you are using a variable with the condition, initialize it before the loop, and increment it within the loop. If you forget to increase the variable, the loop will never end. This will also crash your browser. |
JavaScript Version: | 1.0 |
---|
Loop through the indices of an array to collect the car names from the cars array:
Example above explained:
Loop backwards through the indices of an array:
Using the break statement - Loop through a block of code, but exit the loop when the variable i is equal to "3":
Using the continue statement - Loop through a block of code, but skip the value of "3":
JavaScript Tutorial: JavaScript While Loop
JavaScript Reference: JavaScript do ... while Statement
JavaScript Reference: JavaScript for Statement
JavaScript Reference: JavaScript break Statement
JavaScript Reference: JavaScript continue Statement