TypeScript For Loop

Complete guide to iteration in TypeScript

Types of For Loops in TypeScript

TypeScript supports multiple types of loops for iteration:

  • Traditional for loop - Index-based iteration
  • for...of loop - Iterate over values (recommended)
  • for...in loop - Iterate over keys/indices
  • forEach() - Array method for iteration

1. Traditional For Loop

Syntax: for (initialization; condition; increment) { }
// Basic for loop for (let i = 0; i < 5; i++) { console.log(i); // 0, 1, 2, 3, 4 } // Iterate through array const fruits: string[] = ["apple", "banana", "orange"]; for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); } // Reverse iteration for (let i = fruits.length - 1; i >= 0; i--) { console.log(fruits[i]); } // Step by 2 for (let i = 0; i < 10; i += 2) { console.log(i); // 0, 2, 4, 6, 8 }

2. For...Of Loop (Recommended)

Best for: Iterating over values in arrays, strings, Maps, Sets, and other iterables.
// Iterate over array values const numbers: number[] = [1, 2, 3, 4, 5]; for (const num of numbers) { console.log(num); } // Iterate over string characters const text: string = "Hello"; for (const char of text) { console.log(char); // H, e, l, l, o } // With index using entries() const fruits: string[] = ["apple", "banana", "orange"]; for (const [index, fruit] of fruits.entries()) { console.log(`${index}: ${fruit}`); } // Iterate over Set const uniqueNumbers = new Set([1, 2, 3]); for (const num of uniqueNumbers) { console.log(num); } // Iterate over Map const userMap = new Map([ ["name", "Alice"], ["age", 30] ]); for (const [key, value] of userMap) { console.log(`${key}: ${value}`); }

3. For...In Loop

Note: For...in iterates over enumerable properties (keys/indices). Use with caution on arrays!
// Iterate over object keys const person = { name: "Alice", age: 30, city: "New York" }; for (const key in person) { console.log(`${key}: ${person[key as keyof typeof person]}`); } // With array (returns indices as strings) const colors: string[] = ["red", "green", "blue"]; for (const index in colors) { console.log(`${index}: ${colors[index]}`); // Note: index is a string, not a number! }

4. forEach() Method

// Basic forEach const numbers: number[] = [1, 2, 3, 4, 5]; numbers.forEach((num) => { console.log(num); }); // With index and array numbers.forEach((num, index, array) => { console.log(`Index ${index}: ${num}`); }); // With type annotations const fruits: string[] = ["apple", "banana"]; fruits.forEach((fruit: string, index: number) => { console.log(`${index + 1}. ${fruit}`); });

Comparison Table

Loop Type Best For Break/Continue Async Support
for Index-based, complex control ✅ Yes ✅ Yes
for...of Iterating values (arrays, strings) ✅ Yes ✅ Yes
for...in Object properties ✅ Yes ✅ Yes
forEach() Simple array iteration ❌ No ⚠️ Limited

Loop Control Statements

Break Statement

// Exit loop early const numbers: number[] = [1, 2, 3, 4, 5]; for (const num of numbers) { if (num === 3) { break; // Stop at 3 } console.log(num); // Prints: 1, 2 }

Continue Statement

// Skip current iteration for (let i = 0; i < 5; i++) { if (i === 2) { continue; // Skip 2 } console.log(i); // Prints: 0, 1, 3, 4 }

Practical Examples

Example 1: Sum Array Elements

const numbers: number[] = [1, 2, 3, 4, 5]; let sum: number = 0; for (const num of numbers) { sum += num; } console.log(sum); // 15

Example 2: Filter Even Numbers

const numbers: number[] = [1, 2, 3, 4, 5, 6]; const evens: number[] = []; for (const num of numbers) { if (num % 2 === 0) { evens.push(num); } } console.log(evens); // [2, 4, 6]

Example 3: Nested Loops (2D Array)

const matrix: number[][] = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; for (const row of matrix) { for (const cell of row) { console.log(cell); } }

Example 4: Object Iteration with Type Safety

interface User { name: string; age: number; email: string; } const user: User = { name: "Alice", age: 30, email: "alice@example.com" }; // Type-safe object iteration for (const key in user) { const typedKey = key as keyof User; console.log(`${typedKey}: ${user[typedKey]}`); } // Or using Object.entries() for (const [key, value] of Object.entries(user)) { console.log(`${key}: ${value}`); }

Async Iteration

// for...of with async/await const urls: string[] = ["url1", "url2", "url3"]; async function fetchAll() { for (const url of urls) { const response = await fetch(url); const data = await response.json(); console.log(data); } } // forEach does NOT wait for async operations urls.forEach(async (url) => { const response = await fetch(url); // Runs in parallel! });

Best Practices

Recommendations:
  • Use for...of for iterating array values (most readable)
  • Use traditional for when you need index manipulation
  • Use for...in only for objects, not arrays
  • Avoid forEach() with async/await
  • Use const in loop variables when not reassigning
  • Consider map(), filter(), reduce() for functional approaches

Key Takeaways

Remember:
  • for...of iterates over values (recommended for arrays)
  • for...in iterates over keys/indices
  • Traditional for gives most control
  • forEach() cannot use break/continue
  • Use for...of with async/await, not forEach
  • TypeScript provides type safety in all loop types