Explain the different variants of for loop in TypeScript


In any programming language, we use the loops to execute the same code block repeatedly or multiple times. The loops allow us to write less code to execute the same code block many times.

The for loop is one of the loops in TypeScript. As given below, there are also three different sub-types of the for loop in TypeScript.

  • Normal for loop

  • for-of loop

  • for-in loop

We will learn about all variants of the for loop in this TypeScript tutorial. Also, we will learn how each type of for loop is different from others.

Introduction to normal for loop

We can use the for loop to execute the code block multiple times. Also, we can define howmany times we want to execute the code-block. For every iteration of the for-loop, we can perform different operations on variables.

Syntax

You can follow the syntax below to use the for loop in TypeScript.

for(initialization; condition: step){

   // code block of for loop
}

The for loop executes the code written within the curly braces multiple times.

Parameters

Users can observe in the syntax that for loop takes three different parameters separated by the ‘;’

  • initialization − It is an initialization condition to start the loop. When for loop start, it will invoke all code written before the first semicolon, which means in the initialization block.

  • condition − It is a termination condition for the loop, allowing us to stop the iteration of the for-loop. After every iteration of the for-loop, it checks that if the condition returns true, only for loop goes for the next iteration; otherwise, it stops the iteration.

  • step − It is a step to move the for loop and make changes to the iterable variable after every iteration.

Example 1

In the example below, we have used the for loop to print a message five times. We have initialized the k variable with 1, in the initialization step. After every iteration, for loop checks that if the value of k is less than or equal to 5, it will run the next iteration. Also, the for-loop will increase the k variable by 1 in the step.

In the output, users can see the for-loop runs the code 5 times, which is written in the scope of the for-loop.

// using the for loop to print the message multiple times
for (let k = 1; k <= 5; k = k + 1) {
   console.log("printing the message for " + k + "time");
}

On compiling, it will generate the following JavaScript code −

// using the for loop to print the message multiple times
for (var k = 1; k <= 5; k = k + 1) {
   console.log("printing the message for " + k + "time");
}

Output

The above code will produce the following output −

printing the message for 1time
printing the message for 2time
printing the message for 3time
printing the message for 4time
printing the message for 5time

Example 2

In the example below, we have demonstrated the use of the break and continue keywords with the for-loop. Users can see that we have written true in the termination condition of the for-loop. So, it will never stop the loop.

We have used the ‘break’ keyword to stop the for-loop inside it. In the output, users can observe that the for-loop will not execute the code for the k==1 and jumps to the next iteration.

for (let k = 0; true; k++) {

   // if the value of k==1, the loop will jump to the 

   // next iteration without executing the below code
   if (k == 1) {
      continue;

      // termination condition in the for loop
   } else if (k == 6) {
      break;
   } else {

      //  code to execute
      console.log("The value of iterable k is " + k);
   }
}

On compiling, it will generate the following JavaScript code −

for (var k = 0; true; k++) {

   // if the value of k==1, the loop will jump to the 
   
   //next iteration without executing the below code
   if (k == 1) {
      continue;
      
      // termination condition in the for loop
   }
   else if (k == 6) {
      break;
   }
   else {
   
      //  code to execute
      console.log("The value of iterable k is " + k);
   }
}

Output

The above code will produce the following output −

The value of iterable k is 0
The value of iterable k is 2
The value of iterable k is 3
The value of iterable k is 4
The value of iterable k is 5

Introduction to for-of loop

The for-of loop is the subtype of the for-loop. We can use the for-of loop to iterate through the values of the iterable objects. For example, we can use the for-of loop to iterate through the array and get values from every index.

The for-of loop provides an easy syntax to iterate through the iterable objects than the for-loop.

Syntax

You can follow the syntax below to use the for-of loop to iterate through the iterable objects.

for (let element of iterableArray) {

   // perform some operations with the element
}

In the above syntax, the element is the array element. The for-of loop iterates through every array element from the start index.

Example

In the example below, we have used the for-of loop to iterate through every value of the array. As the string is an iterable object in TypeScript, we have used the for-of loop to iterate through every character of the string.

We can perform any required operation with the string characters or array elements inside the block of the for-of loop.

// Creating the iterable array of type any
let iterableArray: any[] = [
   10,
   "Hi",
   "TutorialsPoint",
   75,
   false,
   true,
   87,
   "JavaScript",
   "TypeScript",
];

// using the for-of loop to iterate through the array
for (let element of iterableArray) {
   console.log("The value of element is " + element);
}

let str: string = "Welcome!";

// iterating through every character of the string
for (let char of str) {
   console.log("The char is " + char);
}

On compiling, it will generate the following JavaScript code −

// Creating the iterable array of type any
var iterableArray = [
   10,
   "Hi",
   "TutorialsPoint",
   75,
   false,
   true,
   87,
   "JavaScript",
   "TypeScript",
];

// using the for-of loop to iterate through the array
for (var _i = 0, iterableArray_1 = iterableArray; _i < iterableArray_1.length; _i++) {
   var element = iterableArray_1[_i];
   console.log("The value of element is " + element);
}
var str = "Welcome!";

// iterating through every character of the string
for (var _a = 0, str_1 = str; _a < str_1.length; _a++) {
   var char = str_1[_a];
   console.log("The char is " + char);
}

Output

The above code will produce the following output −

The value of element is 10
The value of element is Hi
The value of element is TutorialsPoint
The value of element is 75
The value of element is false
The value of element is true
The value of element is 87
The value of element is JavaScript
The value of element is TypeScript
The char is W
The char is e
The char is l
The char is c
The char is o
The char is m
The char is e
The char is !

Introduction to for-in loop

The for-in loops work almost the same as the for-of loop. The for-in loop iterates through the object keys rather than the object values. When we use the for-in loop with the array, it iterates through the array index.

Syntax

You can follow the syntax below to use a for-in loop in TypeScript.

for (let element in iterable) {

   // element can be an object key or array index
}

Example

In this example, we created the object and used the for-in loop to iterate through every object's property. In the output, we can see that the for-in loop prints all object properties.

// creating the object with different key-value pairs
let obj = {
   obj_name: "Shubham",
   hair_color: "black",
   eye_color: "black",
};

// getting all keys of an object
for (let key in obj) {
   console.log("The key is " + key);
}

Output

On compiling, it will generate the same code in JavaScript.

It will produce the following output −

The key is obj_name
The key is hair_color
The key is eye_color

We have learned about different sub-types of the for loop in TypeScript. However, whatever we can do with the for-of and for-in loop, we can use the normal for loop, but for-of and for-in loops give the clear syntax and coder’s iteration towards iterating the iterable.

Also, the difference between the for-of loop and for-in loop is that the for-of loop iterates through the values of iterable, and the for-in loop iterates through the properties of iterable.

Updated on: 17-Jan-2023

203 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements