Typescript

How For-Each Loop Works in TypeScript?

Iterating over the elements of an array or other iterable object is a common programming operation, and TypeScript provides an easy way to do so with a “For-Each” loop that is implemented using the “forEach()” method. It allows the execution of a block of code for each element in an array or iterable object without worrying about the array’s index or length. This makes it a helpful tool for data filtering, mapping, and transformation.

This tutorial will illustrate the working of the For-Each loop in TypeScript.

How Does For-Each Loop Work in TypeScript?

In TypeScript, the “For-Each” loop is implemented with the “forEach()” method, which is a predefined method of the Array object. It is used for iterating through the array elements or other iterable objects. It accepts a callback function as its argument, which is executed for every element in the array.

Syntax
The following syntax is utilized for the For-Each loop:

forEach(callbackFunc)

Here, the “callbackFunc” is the function that is utilized for testing each element in an array.

For example, use the above syntax as:

array.forEach(function(value) {
 // code to execute for each element
});

Example
In the following example, we have a string type array named “lang”:

let lang: string[] = ['JavaScript', 'jQuery', 'Java'];

Call the forEach() method as a For-Each loop to iterate the array and display each element of an array at the console:

lang.forEach(function(value) {
 console.log(value);
});

Transpile the TypeScript file using the “tsc” command:

tsc forEachLoop.ts

The code is now converted into JavaScript, now we will execute the JavaScript file using the given command:

node forEachLoop.js

The output indicates that the array elements have been successfully displayed on the console by iterating the array using the For-Each loop:

The “For-Each” loop is not only used for arrays; it can also be used with any iterable object. Here, we will iterate the object named “stdInfo” having three key-value pairs:

let stdInfo = {
 id : 5,
 name: "Mily",
 age: 15
};

Iterate the object using the For-Each loop with the Object.keys() method to print the object’s properties with their associated values:

Object.keys(stdInfo).forEach(function(key) {
 console.log(key + ': ' + stdInfo[key]);
});

Output

That’s all about the working of the For-Each loop in TypeScript.

Conclusion

The “For-Each” loop is implemented in TypeScript with the “forEach()” method that is utilized for iterating through the array elements or other iterable objects. It accepts a callback function as its argument, which is executed for every element in the array. This tutorial illustrated the working of the For-Each loop in TypeScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.