- Abstract class
- Annotations
- Array
- Asserts
- Class
- Const
- Decorators
- Default parameter
- Dictionary
- Enum
- For loop
- forEach()
- Function
- Generics
- Index signature
- Infer
- Inheritance
- Interface
- Let
- Map type
- Mixin
- Module
- Namespace
- Never
- Object type
- Operator
- Optional parameter
- Promise
- Property
- Tuples
- Type alias
- Type guard
- Type narrowing
- Union
- Utility types
- Var
- Void
TYPESCRIPT
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.
Quick Answer: How to Use for
Loops in TypeScript
TypeScript supports several types of for
loops, each for a different purpose. The most common are the classic for
loop, the for...of
loop, and the for...in
loop.
1. for...of
(To loop over values):
This is the most common and readable way to loop through the elements of an iterable like an array.
const names: string[] = ['Alice', 'Bob', 'Charlie'];
for (const name of names) {
console.log(name);
}
// Outputs:
// Alice
// Bob
// Charlie
2. Classic for
loop (To loop with an index):
Use this when you need to know the index of the current item or want more control over the iteration.
for (let i = 0; i < names.length; i++) {
console.log(`Index ${i}: ${names[i]}`);
}
// Outputs:
// Index 0: Alice
// Index 1: Bob
// Index 2: Charlie
3. for...in
(To loop over object keys):
Use this to iterate over the property names (keys) of an object.
const user = { name: 'Alex', role: 'Admin' };
for (const key in user) {
console.log(key);
}
// Outputs:
// name
// role
For arrays, always prefer for...of
or .forEach()
over for...in
.
Classic For Loop Syntax
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
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
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
break
or 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
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
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
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
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:
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:
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
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:
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:
const ids = new Set([101, 102, 103]);
for (const id of ids) {
console.log(id);
}
Or loop through key-value pairs in a Map:
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
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
for
loop when you need index control. - Choose
for...of
for clean, readable value iteration. - Use
for...in
when 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
map
orfilter
when 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.
Key Takeaways for TypeScript for
Loops
- Use
for...of
for Array Values: This is the most common and recommended loop for iterating through the elements of an array or other iterables when you don't need the index. - Use a Classic
for
Loop for Index Control: When you need the index of each element or want to iterate a specific number of times, the classicfor (let i = 0; ...)
loop is the best choice. - Use
for...in
for Object Keys Only: Thefor...in
loop should only be used to iterate over the keys (property names) of an object. Do not use it for arrays, as it can lead to unexpected behavior. - Type Safety is a Key Benefit: TypeScript provides type safety within loops. In a
for...of
loop over astring[]
, for example, the loop variable is correctly inferred as astring
. break
andcontinue
Work as Expected: You can usebreak
to exit a loop early andcontinue
to skip the current iteration in classicfor
,for...of
, andfor...in
loops (but not in a.forEach()
method).
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.