7️⃣ 🔁 TypeScript Control Flow & Decision Making
Estimated reading: 4 minutes 26 views

🔁 TypeScript — For Loops: Iterate Arrays and Objects with Type Safety

🧲 Introduction – What Are For Loops in TypeScript?

In TypeScript, for loops provide a structured way to iterate over collections, execute repetitive tasks, and process data efficiently. While the syntax is inherited from JavaScript, TypeScript enhances loop usage with strict typing, enabling safer and more predictable iteration over arrays, objects, maps, and other iterable structures.

🎯 In this guide, you’ll learn:

  • The different types of for loops in TypeScript
  • How to iterate over arrays, strings, and objects
  • When to use for, for...in, and for...of
  • Best practices for loop-based programming in TypeScript

🔁 Basic For Loop in TypeScript

The classic for loop uses an index-based structure. It is ideal for arrays and numeric iterations.

✅ Syntax:

for (let i = 0; i < limit; i++) {
  // code block
}

✅ Example:

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

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

📌 Explanation: Loops from index 0 to fruits.length - 1.


🔂 For…of Loop – Iterate Over Values

The for...of loop is used to iterate over iterable values like arrays, strings, maps, and sets.

const colors: string[] = ["red", "green", "blue"];

for (const color of colors) {
  console.log(color);
}

Use When: You want to access array values directly without dealing with indexes.


🧩 For…in Loop – Iterate Over Object Keys

The for...in loop is best for enumerating keys of an object or array.

const user = {
  name: "Alice",
  age: 25,
  role: "admin"
};

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

📌 Type Safety Tip: Use keyof to ensure type correctness when accessing properties dynamically.


🔄 For Loop with Type Annotations

TypeScript lets you annotate the index variable for clarity and precision.

const numbers: number[] = [10, 20, 30];

for (let i: number = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}

✅ Explicit typing helps ensure you’re working with the correct data type.


🧪 Looping Over Strings

Strings are iterable and can be looped over using for or for...of.

const word = "TypeScript";

for (const char of word) {
  console.log(char);
}

📌 This prints each character in the string.


📚 Real-World Use Cases

  • ✅ Iterating over API response arrays
  • ✅ Looping through form inputs and fields
  • ✅ Logging or transforming dataset items
  • ✅ Processing object configuration entries
  • ✅ Running tasks a fixed number of times (e.g., retries, pagination)

⚠️ Common Mistakes and How to Avoid Them

❌ Mistake✅ Fix
Using for...in on arraysUse for or for...of instead for better index control
Not handling object key typesUse keyof and type casting for safe property access
Forgetting loop boundariesAlways check i < array.length to prevent overflow
Ignoring immutability inside loopsAvoid mutating arrays directly inside loops if possible

💡 Best Practices for Using For Loops in TypeScript

  • ✅ Use for loops when you need index control
  • ✅ Use for...of for clean and readable array traversal
  • ✅ Use for...in when iterating over object keys
  • ✅ Prefer const in for...of and for...in when mutation isn’t needed
  • ✅ Keep loops concise and avoid deep nesting when possible

📌 Summary – Recap & Takeaways

TypeScript’s for loop variants offer robust options for iterating over collections with complete type safety. Whether you’re processing arrays, objects, or strings, these loops give you the flexibility and control needed to build reliable and maintainable code.

🔍 Key Points:

  • Use for for index-based iterations
  • Use for...of for value-based iteration over arrays and strings
  • Use for...in for enumerating object keys
  • Leverage type annotations and keyof for object access safety
  • Avoid common pitfalls with loop boundaries and improper access

⚙️ Real-world relevance: For loops are vital in data processing, UI rendering, backend logic, form validation, and control systems.


❓ FAQs – For Loops in TypeScript

❓ What’s the difference between for, for...in, and for...of in TypeScript?

  • for → classic index-based loop
  • for...in → loops over keys of an object
  • for...of → loops over values of an iterable

❓ Is it safe to use for...in on arrays?
⚠️ Not recommended. It loops over indexes as strings and may include inherited properties.

❓ Can I use destructuring inside a for...of loop?
✅ Yes. Example: for (const [key, value] of Object.entries(obj)) {}

❓ Should I use const, let, or var in for loops?
✅ Prefer const for read-only variables, let for index counters. Avoid var.

❓ Can I break or continue a for...of or for...in loop?
✅ Yes, both break and continue work inside these loops.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

TypeScript — For Loops

Or Copy Link

CONTENTS
Scroll to Top