For Loop in TypeScript

Learn via video courses
Topics Covered

Overview

A 'for' loop in Typescript allows code to be performed repeatedly by defining iteration in a control flow statement. The iteration is specified in the header of a 'for' loop, and the body is run once for each iteration. An explicit loop counter or loop variable is frequently declared in the header, allowing the body to determine which iteration is being run. In the subsequent essay on the 'for' loop, we will go into greater detail.

Introduction

We may further manage the flow of our program by looping through chunks of code when a condition is met. Consider a college database in which management wants to send an important notification to every student in the institution who has subscribed to a mailing list.

We would normally input a user's email address, copy-paste a prepared message, and then send the email.

However, one college list may include tens of thousands of pupils. We'd need a method to automate the procedure. Iteration control enables us to code that procedure and then repeat it by looping over all of the students on the list and sending each of them an email.

TypeScript supports three distinct types of loops:

  • do while - This loop is very similar to the while loop, except it begins with a single forced loop.
  • for- This loop repeats a portion of code a specified number of times.
  • While- When the While condition is true, then the loop repeatedly executes a portion of code.

In this article, we will be focusing only on the 'for' loop in Typescript so let's get started.

For Loop in Typescript

A 'for' loop in Typescript is defined as a control statement that executes a particular number of instructions or code or orders multiple numbers of times in the 'for' loop in typescript statement, which is most commonly used in array-like structures such as (arrays, lists) to iterate through the entire array or list and demonstrate one value at a time using the provided condition in the 'for' loop. In general, it is defined as an iteration statement as a condition expressed within the loop to run the code or statements within the 'for' loop in the typescript body with a condition to execute the code again.

Syntax

The syntax of the ''for' loop in Typescript is the same as in other programming languages:

Parameters

  • Starting value: This argument specifies the initial count value for the specified variable to begin the iteration count and maintain track of iterations. As a result, the code in the 'for' loop begins executing from this supplied beginning count number.
  • Condition: this argument is used to describe the logical condition that must be met before the code within the loop is executed.
  • Step increment: this parameter determines how many times after the initial count stated must be repeated according to the supplied condition, and the values of this parameter will be adjusted after each iteration.

This loop will utilize the return statement to break the loop, which is needed to avoid a compile-time error. As a result, this loop returns an array of values or the set of values in which the code is performed within the 'for' loop. There are two other variations of the 'for' loop in Typescript: 'for...of' loop and 'for...in' loop. The for loop is generally used for looping over the values in a set/basket of items, which can also include array-like objects such as a map and set types, while the latter is used for looping over the object properties.

Flowchart

flowchart of for loop in typescript

We can see a design of how the 'for' loop works in the Typescript above, as well as the condition supplied. This form of the blueprint is also known as a flowchart for the 'for' loop, and it depicts the graphical depiction of how the 'for' loop works or the process of flow in Typescript, as well as the algorithm of any 'for' loop code in any program.

Difference Between For And While Loop

For Loop

  • At the start of the loop, statements for initialization, condition checking, and iteration are written.
  • Only when the number of iterations is known in advance is it employed.
  • The loop iterates indefinitely if the condition is not provided in the 'for' statement.
  • Initialization is performed just once, never again.
  • At the outset, a declaration about iterations is written.
  • As a result, it starts to run after the loop's statements have finished running.

Syntax:

Example:

Output:

The 'for' loop in the typescript flowchart is shown below.

typescript flowchart for

While Loop

  • At the start of the loop, startup and condition checks are completed.
  • Only when the number of iterations is unknown is it employed.
  • A compilation error occurs if the condition is not stated in the "while" loop.
  • Initialization takes place each time the loop iterates over itself if the initialization is carried out when the condition is verified.
  • Anywhere inside the loop, the iteration statement can be written.

Syntax:

Example:

Output:

We used the code block to write a single chunk of code that was repeated five times.

Let's dissect the aforementioned scenario in detail.

  • First, we initialize variable i with the value 1. This variable will serve as a counter and let us know where in the loop we are.
  • We then describe our predicament. Run the code in the code block as long as i is less than or equal to 5.
  • We have a straightforward statement that prints the letter i in the code block. By appending ++ to it, we also increase it by one.

What will occur is as follows:

  • i is 1 will be seen by the compiler. As a result, it will print the message on the page and increase i by 1 because the loop condition is true.
  • It will then return to the beginning of the loop and reevaluate the condition. The code block is once again executed because the condition is still true and i, which is now 2, is still less than 5.
  • Until i equals 5, at which point the condition becomes false, and the compiler terminates the loop.

The while loop flowchart is shown below.

while loop flowchart in typescript

How Does the Or Loop Work in Typescript?

The following section explains how the 'for' loop works in Typescript, with examples:

The 'for' loop operates in Typescript the same way it does in any other programming language, such as Python or C/C++. The 'for' loop is the control flow statement that is used in iterations to run a certain set of code or instruction that is written within the 'for' loop, and the first statement of the loop consists of three separate expressions that are defined in the first section.

The first component is used to describe the number of iterations, to begin with; the second part is generally used to specify the condition to run the code within the loop if the condition is fulfilled; and the third part is used to initialize the variable and is only performed once ( if True the code is will be executed, else the loop will not enter the loop body).

The third element is used to declare the count for the increment of the iteration count, which increments the starting count after each iteration indicated in the 'for' statement. If the condition fails, the 'for' loop is ended. The 'for' loop continues to run the supplied set of code or instructions until the condition fails, and the 'for' loop exits the defined number of iterations, at which point the loop is ended. The aforementioned condition is repeated again.

Now, consider the following example to see how the 'for' loop works:

Example 1:

Output:

Explanation: We created a "for" loop in the previous program by creating the variable "n" and setting its initial value to "0." The variable "n" is then iterated from 0 to less than or equal to 3 times, with just one increment after each iteration, and each value is displayed until it achieves the value "3" as stated by the condition. As a result, the output of the preceding code can be seen in the screenshot, which outputs the iteration numbers of how many times the 'for' loop runs the statement within the loop and then terminates when the value of the variable reaches 3.

Example 2:

Output:

Explanation: In the preceding program, we can see that we first declared an array that contains 5 items and is assigned to the variable "Indian_cities"; then, to print the items or elements in the array by iterating over each element, we use a 'for' loop where we initialize the iteration count from 1 which indicates the index number in the given array beginning at index 0; and finally, we use a 'for' loop to print the items or elements in the array by iterating over each element We are publishing the items till the end of the array by utilizing the array function length(), which will take the items until the supplied array length, which in this case is 5. To print each element, we declare the array together with its index, for example, Indian_cities[i].

Types of For Loop in Typescript

Loops are used to run a specific chunk of code several times. In TypeScript, there are two types of loops: Definite Loops (for) and Indefinite Loops (while, do..while)

There are three different types of 'for' loops in TypeScript.

  • for
  • for.. of
  • for.. in

For Loop

The 'for' loop in Typescript runs a specified piece of code a predetermined number of times, as determined by a predetermined conditional expression. This is a common 'for' loop in Typescript that we have been learning about and applying often.

Syntax:

Initialization: statement is executed before the start of the loop, initializing the iteration variable to a specific value that is used to end the loop after a certain number of iterations.

Condition: The termination condition, which specifies when the loop should end, is contained in the condition: statement. Because an erroneous condition might result in a never-ending loop, it is highly crucial!

Update: statement is carried out at the conclusion of every iteration. It modifies the iteration variable's value. The loop is ended when the iteration variable reaches a value that falsifies the iteration condition.

Illustration 1: the Initialization statement, in this case, initializes the iteration variable I with the value 45. Before each iteration, the condition "I <50" is tested, and "i + +" is the update statement that adds one to the iteration variable I at the end of each iteration.

Output:

Illustration 2: In this example, we'll make an array with a few elements and use a 'for' loop in Typescript to access each element in the array.

Output:

For...of Loop

This is a different kind of Typescript 'for' loop in Typescript that operates in a different way. It uses iterable objects like arrays, lists, etc., to operate. It assigns the iteration variable to each element of the iterable after iterating each one. Therefore, if we wish to access elements of an iterable, we don't need to create a 'for' loop in the conventional sense. Instead, we may use a for..of loop.

Syntax:

Illustration 1: Animals array items are retrieved individually and saved in the iteration variable i in this case. So that we don't have to manually access array elements, i save the element of the array at a specific iteration. In addition, the loop runs exactly as many times as the array's length. Thus the termination condition wasn't even a concern.

Output:

When all we need is the contents of an iterable (array, list, or tuple), we may use the for..of loop without having to worry about the array's element indexes.

For..in Loop

The for..in loop functions similarly to the for..of the loop, but instead of assigning the array elements to the iteration variable, the elements' indices are instead assigned. As a result, we obtain the element index at each iteration, which can then be used to access specific array elements or carry out operations that need an index rather than array elements (for example, swapping of two elements).

Syntax:

Illustration 1: The iteration variable, i is used here. It is assigned to each array element's index one by one, beginning with the first index, which is 0, and continuing all the way to the last index, which in this case is 5. JavaScript controls the condition and updates automatically.

Output:

Explanation: As in the code, the result prints i as well as country[i]. We get an index and value at that index in each iteration.

Conclusion

  • We conclude that the 'for' loop is a control statement used to output the repeated items after traversing the specified list.
  • We may repeat pieces of our code by looping across them using iteration control.
  • We have the while, do while, and for loops in TypeScript.
  • When we don't know how many times a loop will repeat, we utilize the while loop. When we know how many times a loop should repeat, we utilize the 'for' loop.
  • The condition block of the statement must contain the 'for' loop's counter and the increment/decrement of that number.
  • We can see that there are for...in and for...of loops, which are 'for' loops in typescript variants identical to the for each loop. These can also travel over a group of items for looping through values and object attributes. Each of the three 'for' loops has benefits of its own.
  • The classic and all-purpose 'for' loop in Typescript can be used for almost anything, but if we're working with iterables (arrays, lists, etc.), utilizing the specialized for..of and for..in variants of the 'for' loop in Typescript can provide cleaner and simpler code.