Iterate over an Array with Index in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 16, 2022

banner

Photo from Unsplash

Iterate over an Array with Index in TypeScript #

Use the forEach() method to iterate over an array with index, e.g. arr.forEach((element, index) => {}). The second parameter the callback function takes is the index of the element in the array.

index.ts
const arr: string[] = ['one', 'two', 'three']; arr.forEach((element, index) => { // 👇️ one 0, two 1, three 2 console.log(element, index); });

The function we passed to the Array.forEach method gets called with each element in the array.

The callback function gets passed the following 3 parameters:

  1. The current element in the array.
  2. The index of the element in the array.
  3. The array on which we called the forEach() method.

The forEach method returns undefined, so it is used to mutate an external variable.

If you need to loop over the array with an index, but return a value on each iteration, use the Array.map method instead.

index.ts
const arr: string[] = ['one', 'two', 'three']; const result = arr.map((element, index) => { return element + index; }); // 👇️ ['one0', 'two1', 'three2'] console.log(result);

The function we passed to the map() method gets called with each element in the array and gets passed the same parameters as forEach().

The map() method returns a new array containing the elements we returned from the callback function.

An important thing to note when using the forEach() method is - you can't use the break keyword to break out of the loop.

If you have to use the break keyword to break out of the loop if a condition is met, use a basic for loop instead.

index.ts
const arr: string[] = ['one', 'two', 'three']; for (let index = 0; index < arr.length; index++) { // 👇️ one 0, two 1 console.log(arr[index], index); if (index === 1) { break; } }

A basic for loop is not as elegant as using forEach(), but enables us to use the break keyword to break out of the loop once a condition is met.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.