TypeScript Definite Loop
In this loop, we know about the number of iterations before the execution of the block of statements. A "for loop" is the best example of this loop. Here, we are going to discuss three types of the loop:
TypeScript for loop
A for loop is a repetition control structure. It is used to execute the block of code to a specific number of times. A for statement contains the initialization, condition and increment/decrement in a single line which provides a shorter, and easy to debug structure of looping. The syntax of for loop is given below.
Explanation of the flow of control in a "for loop" is:
The first expression is the initialization step, which is executed first, and only once. It allows us to declare and initialize the loop control variables.
The next expression evaluates the condition. If it is true, the body of the loop gets executed. If it is false, the loop does not execute, and the flow of control jumps to the next statement just after the "for" loop.
When the body of the "for loop" executes, the flow of control jumps to the increment/decrement statement. It allows us to update the loop control variables. It can be left blank, as long as a semicolon appears after the condition.
Now, the condition is re-evaluated. If it finds true, the loop executes, and the process repeats. When the condition becomes false, the "for loop" terminates which marks the end of the life-cycle.
TypeScript for..of loop
The for..of loop is used to iterate and access the elements of an array, string, set, map, list, or tuple collection. The syntax of the for..of loop is given below.
TypeScript for..in loop
The for..in loop is used with an array, list, or tuple. This loop iterates through a list or collection and returns an index on each iteration. In this, the data type of "val" should be a string or any. The syntax of the for..in loop is given below.
for..of Vs. for..in Loop
Both the loops iterate over the lists, but their kind of iteration is different. The for..in loop returns a list of indexes on the object being iterated, whereas the for..of loop returns a list of values of the object being iterated.
Below example demonstrates these differences: