At times, certain instructions require repeated execution. Loops are an ideal way to do the same. A loop represents a set of instructions that must be repeated. In a loop’s context, a repetition is termed as an iteration.
The following figure illustrates the classification of loops −
A loop whose number of iterations are definite/fixed is termed as a definite loop. The ‘for loop’ is an implementation of a definite loop.
for (initial_count_value; termination-condition; step) { //statements }
Sr.No | Definite Loop & Description |
---|---|
1 | The ‘for’ loop
The for loop executes the code block for a specified number of times. |
2 | The for…in loop
The for...in loop is used to loop through an object's properties. |
3 | The for…of loop
The for…of loop is used to iterate iterables instead of object literals. |
An indefinite loop is used when the number of iterations in a loop is indeterminate or unknown.
Indefinite loops can be implemented using −
Sr.No | Indefinite Loop & Description |
---|---|
1 | The while loop
The while loop executes the instructions each time the condition specified evaluates to true. |
2 | The do…while loop
The do…while loop is similar to the while loop except that the do...while loop doesn’t evaluate the condition for the first time the loop executes. |
Sr.No | Loop Control Statements & Description |
---|---|
1 | The break statement
The break statement is used to take the control out of a construct. |
2 | The continue statement
The continue statement skips the subsequent statements in the current iteration and takes the control back to the beginning of the loop. |
A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. A label can be used with break and continue to control the flow more precisely.
Line breaks are not allowed between the ‘continue’ or ‘break’ statement and its label name. Also, there should not be any other statement in between a label name and an associated loop
Sr.No | Label & Description |
---|---|
1 | Label with Break
A label can be used with break and continue to control the flow more precisely. |
2 | Label with Continue
Line breaks are not allowed between the ‘continue’ or ‘break’ statement and its label name. |