How to iterate over an array in TypeScript



Image not found!!

In TypeScript, you can iterate over an array using various methods. Here are a few examples:

  1. For Loop:

    typescript
    let myArray: number[] = [1, 2, 3, 4, 5]; for (let i = 0; i < myArray.length; i++) { console.log(myArray[i]); }
  2. For...of Loop:

    typescript
    let myArray: number[] = [1, 2, 3, 4, 5]; for (let element of myArray) { console.log(element); }
  3. forEach Method:

    typescript
    let myArray: number[] = [1, 2, 3, 4, 5]; myArray.forEach((element) => { console.log(element); });
  4. Map Method:

    typescript
    let myArray: number[] = [1, 2, 3, 4, 5]; myArray.map((element) => { console.log(element); // Map returns a new array, but if you just want to iterate, use forEach });
  5. Using indexes with forEach:

    typescript
    let myArray: number[] = [1, 2, 3, 4, 5]; myArray.forEach((element, index) => { console.log(`Index: ${index}, Element: ${element}`); });

Choose the method that fits your needs best based on the specific requirements of your code. The forEach method is often preferred for simple iteration over arrays due to its concise syntax.