Cycles. The while () and do-while () tutorial


Consider the cycle while() . This cycle is often called a cycle by condition. In brackets after the word while indicate some boolean expression or value. The cycle will start if the value of this expression is true and will work until this condition is addressed in the false . The general syntax of this loop is:

while (boolExpression) {
      code-to-repeat;
}

Consider a simple example:

var i = 0;
while (i < 10) {
i++;
}


In this type of loop, there is no option that corresponds to the execution of the statement after each iteration ( S2 for for ). Therefore, it is extremely important to implement its change in the body of the cycle. Otherwise, you may encounter a problem бесконечного cycle (looping).

var i = 0;

// everlasting loop - don't do that
while (i < 10) {
  console.log(i);
}



In this example, the value i does not change in the body of the loop, so this condition for the continuation of the loop will always be fulfilled. Note that any cycle written with a loop for() can be rewritten with while() and vice versa. Using a cycle while(), the example from the previous lesson is described as follows:



Cycle do-while() is an analog of the cycle while. The main difference between this type of cycle and while is that he выполнится хотя бы 1 раз , even if the continuation condition of the cycle is false. Consider the general syntax of this loop:

do {
      code-to-repeat;
} while (boolExpression)


As you can see from the syntax, the condition for continuing the loop is written at the end. This means that the code block after do will be executed before the condition is verified. For example, as a result of the cycle

do {
  console.log('test');
} while (false);


a line will be output to the console 'test' . After that, the condition will be checked, which is always equal to false and the cycle will finish. Nevertheless, the first iteration will be executed.

Note also that the considered cycles while, do-while and for are equivalent. This means that a loop written with one of these types can be rewritten with the help of the other two.

Проверьте свои знания
Run the previous job with loops while/do-while