TypeScript for Loop: Syntax, Usage, and Examples
A TypeScript for loop lets you repeat a block of code a specific number of times or iterate through collections like arrays and objects. Whether you’re counting numbers, filtering data, or building a UI dynamically, the TypeScript for loop syntax gives you flexibility and control.
How to Use for Loops in TypeScript
You can write several types of for loops in TypeScript. Each one serves a different purpose. The classic for loop is great for counting. The for...in loop works with object keys, and for...of shines with iterable values.
Classic For Loop Syntax
tsx
for (let i = 0; i < 5; i++) {
console.log(i);
}
This prints numbers 0 through 4. You define a start value, a condition to keep looping, and an increment.
For…in Loop
tsx
const user = { name: 'Alex', age: 30 };
for (const key in user) {
console.log(`${key}: ${user[key as keyof typeof user]}`);
}
This loop accesses each property name in the object. In TypeScript, you use keyof to ensure safe access with type checking.
For…of Loop
tsx
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
console.log(color);
}
This version loops through the values of an iterable like an array or string—not keys.
When to Use a For Loop in TypeScript
The TypeScript for loop is ideal when:
- You need fine-grained control over iteration.
- You want to loop through an array by index.
- You’re looping a fixed number of times.
- You want to work with both keys and values in objects or arrays.
- You need to exit early using
breakor skip usingcontinue.
You’ll find that for loops in TypeScript work well across both frontend and backend use cases, especially where predictable iteration matters.
Examples of TypeScript For Loops in Practice
Looping Over an Array with Index
tsx
const names = ['Taylor', 'Jordan', 'Casey'];
for (let i = 0; i < names.length; i++) {
console.log(`${i + 1}. ${names[i]}`);
}
This gives you both the index and the value, perfect for numbered lists.
For…in Loop with Object Keys
tsx
const settings = { theme: 'dark', notifications: true };
for (const key in settings) {
console.log(`${key} is set to ${settings[key as keyof typeof settings]}`);
}
Use this when you want to work with all the properties of an object.
For…of Loop with Strings
tsx
const message = 'Hi!';
for (const char of message) {
console.log(char);
}
This prints each character in the string—great for text parsing or animation logic.
Combining Conditions with a Loop
tsx
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
console.log(`${i} is even`);
}
}
This pattern is great when filtering inside a loop.
Learn More About Loops in TypeScript
Looping Over Arrays with Type Safety
TypeScript helps you avoid errors by enforcing types:
tsx
const numbers: number[] = [1, 2, 3];
for (const num of numbers) {
console.log(num.toFixed(2));
}
Since num is typed as a number, you get autocompletion and no runtime surprises.
Breaking Out of a Loop
You can use break to stop a loop when you meet a condition:
tsx
for (let i = 0; i < 100; i++) {
if (i === 5) break;
console.log(i); // Stops at 4
}
This gives you full control over when to stop looping.
Skipping Items with Continue
tsx
for (let i = 0; i < 10; i++) {
if (i % 2 !== 0) continue;
console.log(i); // Only even numbers
}
You can skip specific conditions inside a loop with continue.
Chaining With For Each Loop TypeScript
If you prefer a functional approach, combine the forEach method with conditions:
tsx
const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach((fruit, index) => {
if (fruit.startsWith('b')) {
console.log(`${index}: ${fruit}`);
}
});
This isn’t a true for loop, but behaves similarly with a more concise syntax.
Using for Loops with Maps and Sets
You can loop through other data structures too:
tsx
const ids = new Set([101, 102, 103]);
for (const id of ids) {
console.log(id);
}
Or loop through key-value pairs in a Map:
tsx
const roles = new Map([
['admin', 'full access'],
['guest', 'read only']
]);
for (const [role, permission] of roles) {
console.log(`${role}: ${permission}`);
}
This makes the for loop TypeScript-ready for more complex use cases.
Looping Over an Enum
tsx
enum Direction {
North,
South,
East,
West
}
for (const dir in Direction) {
if (isNaN(Number(dir))) {
console.log(dir);
}
}
TypeScript enums can be a little tricky, but for…in can list out the names.
Best Practices for For Loops in TypeScript
- Use the classic
forloop when you need index control. - Choose
for...offor clean, readable value iteration. - Use
for...inwhen working with object keys, but cast types carefully. - Don’t mutate the array you’re looping over unless you know what you’re doing.
- Keep loop bodies short—extract logic into functions if it grows too complex.
- Avoid deeply nested loops when possible. Use array methods like
maporfilterwhen appropriate.
A TypeScript for loop gives you the structure and predictability you need when iterating through arrays, objects, or values. Whether you’re logging, transforming, or validating data, TypeScript’s type system makes your loops safer and your code easier to reason about.