While Loops
While
loops are another type of loops that are used to iterate over a sequence of elements under a certain condition. If the condition is true, the loop keeps executing, but once the condition becomes false, the loop stops executing.
The execution of while loops can be understood by the following illustration.

Consider a similar example of printing the first 10 integers. Unlike for loops, in while
loops a variable needs to be initialized before the loop. This is because the while loop condition requires the value of the said variable. In the example below, we initialize i
before the loop, and keep incrementing it until all the first 10 integers are printed.
1var i = 0;
2while (i < 10){
3 console.log(i);
4 i++;
5}
Note:
++
is thepost-increment
operator. It is used when a variable needs to be incremented by 1. This is a common notation that you will see in while loops!
Let's look at another example where we specify a different condition. This loop keeps executing until it encounters an odd element from the list numbers
.
1// loop stops once odd number is encountered from the list
2var i = 0;
3var numbers = [0, 2, 4, 5, 7];
4while ((numbers[i] % 2) == 0){
5 console.log(numbers[i]);
6 i++;
7}
8console.log("Odd number found!");