create a loop with an index in typescript

To create a loop with an index variable in TypeScript, you can use either a for loop or a while loop.

For loop with index variable

index.ts
for (let i = 0; i < array.length; i++) {
  console.log(`The element at index ${i} is ${array[i]}`);
}
102 chars
4 lines

In this for loop, the variable "i" is initialized to 0, and the loop will continue as long as the index is less than the length of the array. The index is incremented by 1 in each iteration of the loop.

While loop with index variable

index.ts
let i = 0;
while (i < array.length) {
  console.log(`The element at index ${i} is ${array[i]}`);
  i++;
}
106 chars
6 lines

In this while loop, the index variable "i" is initialized to 0 before the loop, and the loop will continue as long as the index is less than the length of the array. The index is incremented by 1 in each iteration of the loop, just like in the for loop.

Both loops achieve the same result - iterating over an array with an index variable.

gistlibby LogSnag