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:
Here, the “callbackFunc” is the function that is utilized for testing each element in an array.
For example, use the above syntax as:
// code to execute for each element
});
Example
In the following example, we have a string type array named “lang”:
Call the forEach() method as a For-Each loop to iterate the array and display each element of an array at the console:
console.log(value);
});
Transpile the TypeScript file using the “tsc” command:
The code is now converted into JavaScript, now we will execute the JavaScript file using the given command:
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:
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:
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.