JavaScript while
Statement
JavaScript Statements Reference
Example
The loop in this example will continue to run as long as the variable i is less than 5:
text Output result:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
More examples are included at the bottom of this article.
Definition and Usage
The while
statement executes a loop as long as the specified condition is true.
The loop will continue to execute the code block as long as the specified condition remains true.
JavaScript supports different types of loops:
- ** - Loops a block of code a specified number of times
- ** - Iterates over the properties of an object
- while - Loops a block of code while a specified condition is true
- ** - Also loops a block of code while a specified condition is true, but executes the code block once before checking the condition
Tip: Use the break statement to exit a loop, and the continue statement to skip the current iteration and proceed to the next one.
Browser Support
Statement | |||||
---|---|---|---|---|---|
while | Yes | Yes | Yes | Yes | Yes |
Syntax
Parameter Values
Parameter | Description |
---|---|
condition | Required. Defines the condition for executing the loop. If it returns true, the loop continues; if it returns false, the loop stops. <br> <br> Note: If your condition always evaluates to true, the loop will never end and may cause the browser to crash. <br> <br> Note: If you forget to increment the value of the variable used in the condition, the loop will never end and may cause the browser to crash. |
Technical Details
| JavaScript Version: | 1.0 | | --- | --- |
More Examples
Example
Loop through the indices of an array and output car names:
Example Explanation:
- We initialize the variable before the loop starts (var i = 0;)
- Then, we define the loop condition. As long as the variable i is less than the length of the array (4)
- Each time the loop executes, the variable is incremented by 1 (i++)
- Once the variable is no longer less than the array length, the condition becomes false, and the loop terminates.
Example
Loop starting from the last index of the array:
Example
Using the break statement - Exit the loop when the variable i equals 3:
Example
Using the continue statement - Skip the iteration when the variable is "3":
Related Pages
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