loop over an array in typescript

There are multiple ways to loop over an array in TypeScript, but in this answer, we will cover two commonly used approaches - using a for loop and using the forEach method.

Using a for loop:

index.ts
const myArray: number[] = [1, 2, 3, 4, 5];

for (let i = 0; i < myArray.length; i++) {
    console.log(myArray[i]);
}
118 chars
6 lines

In the above example, we are using a for loop to iterate over the array myArray. The loop continues until the i variable reaches the length of the array. Within the loop, we can access each element of the array using the index i.

Using the forEach method:

index.ts
const myArray: number[] = [1, 2, 3, 4, 5];

myArray.forEach((element) => {
    console.log(element);
});
105 chars
6 lines

The forEach method is another way to iterate over an array in TypeScript. In the above example, we are calling the forEach method on myArray and passing a callback function as an argument. This function will be called for each element in the array, and we can access each element using the element parameter.

gistlibby LogSnag