JavaScript ‘while Loops’
This article is a brief follow-up on a previous, related post. See the link below for further reading on a similar topic.
Another JavaScript loop that is commonly used to perform the same action again and again is the while loop. This article will cover both the ‘while’ statement and the ‘do/while’ statement, as well as a comparison of the standard ‘for’ loop and ‘while’ loop.
While Loop
A while loop is used to execute a statement or code block repeatedly as long as the provided expression evaluates to ‘true’. As soon as the expression evaluates to ‘false’, the loop ends. The following image represents the flow of a standard ‘while’ loop.
And the syntax is very simple:
Example:
In this example, a counter is initiated with a value of 1. The while loop will execute the code block as long as the expression ‘counter < 5’ evaluates to ‘true’. Therefore, when the counter is equal to 1, 2, 3, and 4 the ‘while’ loops will console.log the provided sentence, inserting the current value of the counter each time. Then the counter is increased by 1 (by the line ‘counter++’) and move on to the next iteration of the loop. Once the counter is equal to 5, the expression in the ‘while’ loop will evaluate to ‘false’, which ends the loop.
Result:
If the expression provided to the ‘while’ loop never evaluates to ‘true’, the code block inside the loop will not run. Example:
Since ‘count’ is initialized at 1, the expression in the ‘while’ loop is ‘false’. The code inside the ‘while’ loop does not run.
Get Brad Newman’s stories in your inbox
Join Medium for free to get updates from this writer.
Result:
Do/While Loop
The ‘do/while’ statement is a variant of the while loop. With this statement, the code block is executed once before the expression provided the the ‘while’ statement is evaluated. Then, the code block is executed repeatedly until the expression evaluates to ‘false’. This type of loop will always be executed at least once, even if the expression is false, because the code block is executed before the expression is evaluated.
The syntax for this loop is also very simple:
Example 1:
Result:
Example 2:
Result:
Unlike the standard ‘while’ loop, the code block in Example 2 is executed once despite the expression evaluating to ‘false’ on the first iteration.
Comparison
Those who are familiar with the standard ‘for’ loop and the standard ‘while’ loop may notice some similarities between the two loops. A ‘while’ loop is essentially the same as a ‘for’ loop, with the first and third expressions of the ‘for’ statement omitted. The ‘while’ loop example above would work the same with a ‘for’ loop using the same expression as the second statement and leaving out the first and third statements:
As expected, this yields the same result as the ‘while’ loop:
For further reading on ‘while’ loops, please see:








