JS: do while | JavaScript
JavaScript do while
do
while
loop defines block of statements to iterate until the condition given in while
at the end of the loop.
var i = 0;
do{
console.log(i++);
}
while(i < 10);
0
1
2
3
4
5
6
7
8
9
do
-while
made first iteration with checking the condition. Checked the condition 9 times. 9th time, the loop exited (broken) because the condition i < 10
became false
.
do
-while
executes at least once
do
console.log('do-while iterates at leasts once!');
while(false);
do-while iterates at leasts once!
Even the condition is false
but the the console.log
statement will be executed because the statement is checked later by while
. The above code will always running if the condition was true
instead of false
.
Comparing while
and do
-while
loops difference
while
loop checks the condition first and executes the statement(s) in the block until the condition remainstrue
.do
while
executes the statement(s) in the block at least once.- The do-while loop keeps iterating (repeating) the the block of statements until the condition in
while
remainstrue
. do
while
exited (broken) if the condition inwhile
becomesfalse
.
Summary
do
while
executes statement(s) at least once in any case.while
is required at the end ofdo
-while
loop.