A while loop is created using while
keyword followed by a condition and a set of statements that are executed as a part of the loop enclosed between curly braces.
Syntax
while(condition) {
// loop statements
}
Loop keeps on iterating till the loop condition remains true
.
Curly braces are not required if there is only one statement in the loop.
Example
Suppose you want to print a message to the console 5 times. Example of a while
loop to do this is given below.
// initialize loop variable let index = 0; while(index < 5) { console.log("Learning javascript: " + index); // increment loop variable index++; }
Above code initializes a loop variable to 0. Loop condition uses this variable as a condition and executes till the value of this variable remains less than 5. Note that the value of this variable is incremented inside the loop. As the value of variable becomes 5, the loop condition index < 5
becomes false
and the loop is terminated.
Output
Learning javascript: 0 Learning javascript: 1 Learning javascript: 2 Learning javascript: 3 Learning javascript: 4
Usage
A while
loop can be used to perform different programming tasks. Some of those are given below.
1. Displaying even and prime numbers within a range.
2. Calculating factorial of a number.
3. Displaying prime numbers within a range.
4. Reversing a number.
5. Iterating over an array or object.
Nested while loop
A while
loop can also contain another while
loop. This is called nested while
loop. In a nested while
loop, the inner loop body executes just like another statement, that is, multiple number of times.
Total number of executions of inner loop = Outer loop execution count * Inner loop execution count
Example,
let outerIndex = 0, totalCount = 0; while(outerIndex < 5) { let innerIndex = 0; while(innerIndex < 5) { innerIndex++; totalCount++; } outerIndex++; } console.log('Inner loop execution count: ' + totalCount); // prints 25
Above code contains a nested while loop in which the inner loop executes for 25 times(5 times for outer loop and 5 times for inner loop).
for and while loops: Comparison
Both loops perform the same task of executing a set of statements repeatedly but there are differences between the syntax of these loops. They are:
1. for
loop can contain initialization part of loop variable as a part of the loop itself. Example, for(let index = 0; index < 5; index++){}
. But in while
loop, the loop variable is initialized before the loop, it can not be the part of loop itself.
2. Similarly, loop variable increment in for
loop can be the part of loop declaration but not in while
loop. In while
loop, the variable can only be incremented inside the loop body.