TypeScript Loops

for Loop

Classic C-style loop; best when you know exactly how many times you want to run.

Basic Structure

for (initialization; condition; update) {
    // code block
}

Example

Loading...
Output:

while Loop

Useful for looping until a condition is no longer true.

Basic Structure

while (condition) {
    // code block
}

Example

Loading...
Output:

do...while Loop

This loop ensures the body runs at least once before checking the condition.

Basic Structure

do {
    // code block
} while (condition)

Example

Loading...
Output:

for...of Loop

Preferred for looping through arrays and strings.

const fruits = ["apple", "banana", "cherry"];

for (const fruit of fruits) {
  console.log(fruit);
}

for...in Loop

Use for...in when you need to access object keys. Always use keyof for safe typing.

const user = { name: "Alex", age: 30 };

for (const key in user) {
  console.log(key, user[key as keyof typeof user]);
}

break and continue

continue skips the current loop iteration, break exits the loop.

for (let i = 0; i < 5; i++) {
  if (i === 3) continue;
  if (i === 4) break;
  console.log(i);
}
Output:
0
1
2

Best Practices

  • Prefer for...of for array iteration.
  • Don’t alter the loop index manually unless required.
  • Use break sparingly for clean logic.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic