Note: This post is work-in-progress learning-note and still in active development and updated regularly.
In JS programming, like in other programming languages, there would a need to do certain task repeatedly, for example to run a block of code to perform repetitive tasks. JS loops offer easy way to perform same task repetitively. There are different kinds of loops but all do same thing: repeat certain actions for a number of times.
The MDN Document list different kinds of Loops & Iterations. In our previous learning post we discussed Conditional Statements to perform certain tasks repeatedly based on true
or false
return of specified conditions. In this learning-note post, we will discuss while
and do..while
statements, which are similar to conditional statements. While conditional statements are run only once, a loop executes multiple times until the conditions evaluates true
.
Other common type of JS loops are for
, for..in
, for..of
statements which will be discussed in separate learning post – Understanding JavaScript For Loops.
While statement
The while
statements are conditional statements, similar to the if
statements. Before starting an iteration, conditions are evaluated and if exit-condition it returns true
the code body (statements) is executed until it is returned false
.
Basic Syntax
//basic syntax
while (condition) { // exit condition
statement; //code block to run
statement; // code block to run
....
}
A basic syntax of a while
statement is shown above. If the exit condition (line 2) becomes false
then code execution stops and passed to next to while
statements.
- condition : the condition test occurs before code block is executed. If condition is
true
, the code block is executed and condition is tested again. As long as the condition istrue
the body code is executed until the condition returnsfalse
. - statement : the code block to be executed as long as the exit condition evaluates
true
.
Example 1
In the following example from the MDN, the while
statement executes as long as a
is less than 4
.
//initialize var to zero
let a = 0;
let b = 0;
// loop through while
while (a < 4) {
a++;
b += a;
}
//OUTPUT
10
In the example above, the a
& b
variables are initialized to zero
. With each iteration, the loop increases a
(line 6) and adds that value to b
(line 7). Lets examine these iterations part step by step:
- Step 1: The iterator,
a
&b
start atzero
(lines: 2-3). Execution condition is evaluated which to run & re-run the loop untila
is smaller than5
(line 4). - After the first pass:
a
= 1 andb
= 1 - After the second pass:
a
= 2 andb
= 3 - After third pass:
a
= 3 andb
= 6 - After the fourth pass:
a
= 4 andb
= 10
After the fourth pass, the condition a < 4
is no longer true
and the loop terminates.
Example 2
In the example below, the condition (line 1) never becomes false
. Such iterations are called infinite loops. A loop condition MUST become false
otherwise the loop will never terminate.
// Initiate an infinite loop
while (true) { //exit condition
// execute code forever
}
Avoid Infinite Loops: When the condition of the while
statement is set to true
the code will run forever. It would crash the browser or computer.
Do..While Statement
The do..while
loop statement is variant of the while
loop statement. In case of the while
loop, condition is evaluated first before execution of code block, where as in do..while
loop the code block is executed before it evaluates whether condition is true
. If the condition is true
then it re-executes as long it the condition is true
and stops when it the condition is false
.
Basic Syntax
//basic syntax
do {
statement; //code block to run
statement; //code block to run
...
} while (condition); //exit condition
The basic do..while
syntax is shown above.
- statement : executed once before condition is evaluated and the code block is re-executed until the condition evaluates
false
. - condition : The exit condition is evaluated after each iteration and re-executed as long as the condition evaluates t
rue
. If the exit condition evaluatesfalse
, the loop iteration stops and passes to next block of code.
Example 1
In the following example from the MDN, the do
statement executes at least once and thereafter re-iterates until a
is less than 5
.
//initialize var a to zero
let a = 0;
// loop through do..white
do {
a += 1; //increment by 1
console.log(a);
} while (a < 5); // exit condition
//OUTPUT
1
2
3
4
5
In the example above, var a
is initialized to zero (line 2). The do statement block executes (line 5) as a result value of a
increases to 1 (line 5) and printed in console (line 9). After this first iteration, it check the condition a < 5
(line 7) and since it is less than 5 it returns true
and the loop body (line 5) re-executes which increases the value a
to 2 and so on. After the fifth pass, when value of a
is no longer smaller than 5, the condition fails and the loop terminates.
Example 2
In the following example, the do..while
loop statement is applied to list array items using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length" target="_blank" rel="noopener">array.length</a>
property discussed in array learning-note post.
//initialize cars array
let cars = ["Toyota", "Ford", "GMC", "Honda"];
let x = 0;
// loop through do..while
do {
console.log(cars[x]);
x++;
}
while (x < cars.length)
//OUTPUT
Toyota
Ford
GMC
Honda
In the example above, cars
array with four car items is loop through with do...while
statement and array.length
property (lines 4-8) to printout array list (lines 10-13).
Important. With for
— as with all loops — you must make sure that the initializer is iterated so that it eventually reaches the exit condition. If not, the loop will go on forever, and either the browser will force it to stop, or it will crash. This is called an infinite loop [Source: MDN]
Break/Continue Statements
The break and continue statements are used to either break “out of” the loop or “jump over” one iteration of the loop. The break statement is very useful to terminate an infinite loops.
Note: Use of break
and continue
keyword in the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for" target="_blank" rel="noopener">for</a>
statements will be discussed in a separate post.
The Break Statement
To quote from the MDN documentation, “the break statement terminates the current loop, switch
, or label
statement and transfers program control to the statement following the terminated statement“.
The break
statement uses optional label
statement (discussed below) which allows to terminate a labeled
statement from the loop. The break
statement should be nested within the reference label
statement.
Example
In the example below, a break
statement is used to break out of while
statement in the loop.
//initialize var to zero
let x = 0;
//loop with while
while (x < 6) { //exit condition
if (x === 3) {
break; //use of break
}
x = x + 1; //increment by 1
console.log(x);
}
//OUTPUT
1
2
3
In the example above, a break
statement (line 7) terminates the while
loop when the condition value of x
reaches 3
. When x===3
, the break
statement is kicked in and the iteration terminates out of the loop, as shown in the out put (lines: 13-15).
The Continue Statement
Quoting from the MDN Documentation “the continue statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.”
In contrast to the break
statement discussed above, the continue
statement does not terminate the loop but it jumps back to the while
condition or expression update in the for
loop.
Just like in the break
statement, the continue
statement can also be combined with the label
statement, which allows to jump to the next iteration of a labelled
loop statement.
Example
In the example below, a continue
statement is nested within a while
loop when a defined condition is returned true
.
//basic syntax
continue [label]; //use label parameter if not used in a loop
//initialize variables
let a= 0;
let b = 0;
// while loop
while (a < 5) { //exit condition
a++;
console.log(b);
// use continue to skip iteration
if (a === 3) { //continue condition
continue;
}
//reassign b value
b += a;
}
//OUTPUT - skips 3rd iteration
0
1
3
7
12
In the example above from the MDN, the while
loop with continue
key word is used. When the value of a
is 3 it skips the iteration moves to the next iteration thus skipping an output value (6) of third iteration.
The Label statement
The label
statement as referred in the MDN Documentation can be used with break
or continue
statements. It is prefixing a statement with an identifier which you can refer to.
A label
statement can be used to identify a loop and combining with the break
or continue
statements a execution of a loop could be interrupted or continued.
Example
In the following simple example of a for
loop, variable a
is declared and initialized to zero
(line 2). It first evaluates if a
is less than 4
and returns true
it executes statements and a
is increment by 1
after each iteration. When condition evaluates false
loop execution terminates.
//initialize variable
let a = 0;
//looping with for
for (a = 0; a <= 4; a++){
console.log(a);
}
//OUTPUT
0
1
2
3
4
In the example above a simple for statement loop is used to execute 4 iterations, with the value of a increasing from 0 to 4. After each iteration, it will log the value of a
on the console.
Now lets use the label
statement to name the above loop.
//initialize var to zero
let a = 0;
//iterate with for
even: //label name
for (a = 0; a <= 6; a++){
if (a % 2 == 1) continue even;
console.log(a);
}
//OUTPUT
0
2
4
6
In the example above, our previous for
loop example is modified by adding a label
named even
(line 16). In line 18, a conditional statement with a % 2 == 1
is added with if
statement and followed by continue
even
(label name of the outer loop). What does this internal if
loop does is that it evaluates value of a
after each iteration and when a%2
is 1
(or odd value) then it instructs to skip the iteration with continue
statement and move to the next iteration. Therefore, all odd values are skipped and only even values of a
are printed on the console (lines: 22-25).
The label
statement is especially useful in nested loop because it allows to use break
or continue
statements to selectively terminate or continue some parts of loop execution.
Note: Labeled
loops or blocks are very uncommon. Usually function calls can be used instead of loop jumps. Source: MDN.
Wrapping Up
In this learning-note post use of while
loop, do..while
loop to iterate some defined repetitive tasks were examined. Use of the break/continue
statements to either break “out of” the loop or “jump over” one iteration of the loop were examined. Another common type of loop using for
statement will be discussed separately in the next learning-note post.
Related Post: Understanding JavaScript For Loops
Useful Resources & Links
While preparing this post, I have referred the following references extensively. Visit original link for additional information.
-
- Loops and Iterations | MDN JavaScript Guide
- Looping Codes | MDN Documentation
- Exploring JavaScript Iteration | FreeCodeCamp
- Loops: while and for | The Modern JavaScript Tutorial