TypeScript forEach Loop: The Basics of forEach Method in TS

Understanding TypeScript forEach loop

The forEach() loop in TypeScript is a method that is used to execute a certain function for each item in an array.

The forEach method is available on all arrays and it provides a clean and simple way to iterate through each element in an array.

In simple words, you can utilize the forEach loop to iterate the elements in an array, set, map, or list in TypeScript.

Syntax:

Here’s the basic syntax of the forEach method.


array.forEach(callback[, thisObject];

Parameters:

  • callback: This is the function that operates on each array element.
  • thisObject: Used to indicate the present status of the element in the array.

The function you use with forEach can take in three things if you want: the item (each thing in the array), the index (where each thing is in the array), and the array itself.

How to Use forEach in TypeScript?

The forEach loop in TypeScript is used to iterate over array elements.

For example:

const grades: number[] = [80, 85, 90, 95, 99];

grades.forEach((number) => {
  console.log(number);
});

Output:

80
85
90
95
99

How to break forEach loop in TypeScript?

The forEach loop in TypeScript can’t be stopped or break the forEach loop. Once initiated, it will execute for every element in the array without exception.

This characteristic makes it inappropriate for scenarios where you wish to halt the loop contingent on a specific condition.

If you want to be able to break the loop, you have to use a for..of loop.

To understand here’s the illustration:

// Assuming group.subjects is an array of strings
let group = {
  subjects: ['Programming', 'Web Development', 'Software Development']
};

for(let subject of group.subjects){
  if (subject == 'Programming') {
    console.log('Found Programming!');
    break;
  } else {
    console.log(subject);
  }
}

Output:

Found Programming!

Remember:

  1. Does not return a value:

The forEach method always returns undefined. If you need to transform the array and return a new array, use a map.

  1. Cannot break out early:

Unlike for loops, you cannot break out of a forEach loop early. If you need to do so, consider using a for loop or some/every method.

  1. Side effects:

The primary use of forEach is for side effects, like logging or modifying external variables.

Conclusion

In conclusion, we’re done exploring the forEach loop in TypeScript, which is a method that is a good way to go through each item in an array when you want to do something extra.

Knowing what it can and can’t do helps you decide when to use it or when to use something else.

I hope this article has helped you understand the forEach loop.

If you have any questions or inquiries, please don’t hesitate to leave a comment below.

Leave a Comment