In this JavaScript tutorial, you will learn about JavaScript Iterative Structures, while loop and do..while loop explained along with syntax and examples.
while loop:
This looping structure is used when a programmer wants the block of code to execute until the condition specified remains true.
The general format of while loop in JavaScript is as follows:
|
An example used to understand the while loop of JavaScript:
|
The output of the above example is
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Value is: 10
Value is: 11
Value is: 12
Value is: 13
Value is: 14
Value is: 15
In the above example, the variable exfor initializes with a starting value of 1. The value of exfor is compared with the condition specified in while loop. Since 1 is less than 15, it returns a true value and the block of code inside the while loop executes, prints the value of exfor (1) and increments the value of variable exfor (resulting in value 2) for exfor. Again, the control transfers to the beginning of while loop and, again, the current value of exfor (2) is compared with 15 and since it returns true again, the block of code inside the while loop executes. This proceeds until the value of exfor is 16. When the value of variable exfor reaches 16, it is compared with the condition and, since 16 is greater than 15, the while condition returns false and control passes out of while loop.
do..while loop:
The do….while loop has similar functionality to the while loop. The only difference being that the condition is placed at the end of the block of statements in a do..while loop. As a result, the block of code executes at least once. If, after the first run, the condition is true, the block of code executes again and continues until the condition becomes false.
The general format of do…while loop in JavaScript is as follows:
|
for example:
|
The output of the above program is
Value is: 1
In the above program, the value of variable exfor is first initialized to 1, then the do block executes, resulting in the printing of the value of variable exfor. Then the value of exfor increments, giving the variable exfor a value of 2. The condition in while loop executes, giving a value of 2 (not less than one), returning a false value. The control is then moved out of the do..while loop structure.