JavaScript while Loop
while
statement to create a loop that executes a block as long as a condition is true
.Introduction to the JavaScript while loop statement
The JavaScript while
statement creates a loop that executes a block as long as a condition evaluates to true
.
The following illustrates the syntax of the while
statement:
while (expression) {
// statement
}
Code language: JavaScript (javascript)
The while
statement evaluates the expression
before each iteration of the loop.
If the expression
evaluates to true
, the while
statement executes the statement
. Otherwise, the while
loop exits.
Because the while
loop evaluates the expression
before each iteration, it is known as a pretest loop.
If the expression
evaluates to false
before the loop enters, the while
loop will never execute.
The following flowchart illustrates the while
loop statement:
Note that if you want to execute the statement a least once and check the condition after each iteration, you should use the do…while statement.
JavaScript while loop example
The following example uses the while
statement to output the odd numbers between 1 and 10 to the console:
let count = 1;
while (count < 10) {
console.log(count);
count +=2;
}
Code language: JavaScript (javascript)
Output:
1
3
5
7
9
How the script works
- First, declare and initialize the
count
variable to1
. - Second, execute the statement inside the loop if the
count
variable is less than10
. In each iteration, ouput the count to the console and increase the count by2
. - Third, after
5
iterations, thecount
is11
. Therefore, the conditioncount < 10
isfalse
, the loop exits.
Summary
- Use a
while
loop statement to create a loop that executes a block as long as acondition
evaluates totrue
.