Creating code with three different types of loops (While / For / Do..While)
Loop statement in programing language is very handy. There may be a situation when you need to execute codes or group of statements multiple times. Loops allow us for more complicated execution paths. In this blog post, I will explain three different types of loops: while loop, for loop, and do/while loop.
## While Loop
A while loop statement repeatedly executes a block of code as long as a given condition is true.
The condition in the while loop statement is boolean expression. When executing, if the condition is true, the loop body will be executed. It will repeat as long as the expression result is true.
- Initialization is outside the loop body.
- Iteration is inside the loop body.
## For Loop
The for statement creates a loop with 3 expressions.
A for loop is useful when you know how many times a task is to be repeated.
A for statement can be simplified with for/of or for/in statement. The for/of statement loops through the properties of an array, and for/in statement loops through the properties of an object.
The example above can be simplified to the following using for/of statements:
- Initialization, condition, and iteration are initially executed in order.
- Each step ends with a semicolon (;)
- Iteration can be left blank with a semicolon at the end.
## Do/While Loop
A do/while loop is similar to a while loop, except that a do/while loop is always executed at least once.
- Initialization is outside the loop.
- Iteration is inside the do statement.
- Condition is inside the while statement.
- The loop is always executed at least once.