TypeScript for loop
A TypeScript for loop repeatedly executes a block while its condition remains true. It is commonly used when a program needs a numeric counter, an array index, a fixed range, or controlled iteration with break and continue.
TypeScript supports the JavaScript loop forms, including the classic for loop, for...of, and for...in. They serve different purposes: for...of reads iterable values, while for...in reads enumerable property keys.
TypeScript for loop syntax
A classic for statement contains initialization, a continuation condition, and an update expression. These three parts are separated by semicolons.
Syntax – TypeScript for loop
Following is the syntax of for loop in typescript :
for (looping_variable; condition; update_looping_variable) {
// block of statements
}
- Initialization: Runs once before the first condition check. It usually declares a counter with
let. - Condition: Runs before every iteration. The loop continues when this expression evaluates to true.
- Update: Runs after each completed iteration. It commonly increments or decrements the counter.
- Loop body: Contains the statements executed during each iteration.
Any of the three header expressions may be omitted, but the separating semicolons remain required. When the condition is omitted, the loop continues indefinitely unless its body exits with break, return, or throw.
TypeScript for loop with a numeric counter
The following loop initializes a counter at 1, checks that it is less than 10, and increments it after every iteration. The body therefore runs for the values 1 through 9.
Typical Example of TypeScript for loop
Following is a typical example of for loop, where a counter is initialized, and incremented by 1 each time the loop is executed and the condition is such that the counter does not exceed a limit value.
example.ts
for(var counter:number = 1; counter<10; counter++){
console.log("for loop executed : " + counter)
}
Output
for loop executed : 1
for loop executed : 2
for loop executed : 3
for loop executed : 4
for loop executed : 5
for loop executed : 6
for loop executed : 7
for loop executed : 8
for loop executed : 9
TypeScript for loop with an array index
Use a classic loop when both the element value and its numeric index are needed. Array indexes begin at zero, so the condition should normally be index < array.length.
const cities: string[] = ["Delhi", "Chennai", "Kolkata"];
for (let index = 0; index < cities.length; index++) {
console.log(`${index}: ${cities[index]}`);
}
Output
0: Delhi
1: Chennai
2: Kolkata
Using < rather than <= prevents an attempt to access the element at cities[cities.length], which is outside the array and produces undefined at runtime.
TypeScript for loop over a numeric range
TypeScript has no dedicated range operator for loops. Define the starting value, limit, and step in a classic for statement. The following example processes the even numbers from 2 through 10.
for (let number = 2; number <= 10; number += 2) {
console.log(number);
}
To count downward, start with the larger value and decrease the counter. The condition must agree with the update direction; otherwise, the loop may never execute or may become infinite.
for (let seconds = 3; seconds >= 1; seconds--) {
console.log(seconds);
}
TypeScript for…of loop for array values
A for...of loop reads values from an iterable object. It is usually the clearest loop for arrays, strings, sets, maps, and other iterables when a numeric index is not required.
for (const value of iterable) {
// use the current value
}
This example iterates over an array of typed objects. Within the loop, product has the Product type, so its declared properties are checked by the compiler.
interface Product {
name: string;
price: number;
}
const products: Product[] = [
{ name: "Notebook", price: 80 },
{ name: "Pen", price: 20 }
];
for (const product of products) {
console.log(`${product.name}: ₹${product.price}`);
}
Output
Notebook: ₹80
Pen: ₹20
TypeScript for…in loop for property keys
A for...in loop enumerates an object’s enumerable string property keys, including inherited enumerable properties. It is intended primarily for object keys rather than array values.
for-in loop
When for...in is applied to an array or tuple, the loop variable receives property keys such as "0" and "1", not the element values themselves. A value can then be read with indexed access such as arr[item]. For normal array-value iteration, prefer for...of.
TypeScript for…in syntax
Following is the syntax to use for-in loop.
for (var item in dataset) {
// block of statements
}
TypeScript for…in loop with an object
The following example demonstrates the intended key-oriented use of for...in. The ownership check prevents inherited enumerable properties from being processed.
const scores: Record<string, number> = {
mathematics: 88,
science: 91,
english: 84
};
for (const subject in scores) {
if (Object.prototype.hasOwnProperty.call(scores, subject)) {
console.log(`${subject}: ${scores[subject]}`);
}
}
Example for-in loop with array
This earlier pattern demonstrates how the key returned by for...in can be used to access an array element. It works for this simple array, but for...of is preferable when only the values are required because it expresses that intent directly.
example.ts
var arr:number[] = [10, 65, 73, 26, 44]
for(var item in arr){
console.log(arr[item])
}
Output
10
65
73
26
44
Upon compiling to JavaScript, tsc generates following .js code.
example.js
var arr = [10, 65, 73, 26, 44];
for (var item in arr) {
console.log(arr[item]);
}
Example for-in loop with tuple
The same key-based behavior applies to a tuple. Each key is used to retrieve the corresponding tuple element in the loop body.
example.ts
var student = [10, "John", "Spanish"]
for(var item in student){
console.log(student[item])
}
Output
10
John
Spanish
Upon compiling to JavaScript, tsc generates following .js code.
example.js
var student = [10, "John", "Spanish"];
for (var item in student) {
console.log(student[item]);
}
TypeScript for, for…of, for…in, and forEach comparison
| Loop form | Provides | Suitable use | Supports break and continue |
|---|---|---|---|
for | A controlled counter | Indexes, numeric ranges, custom steps | Yes |
for...of | Iterable values | Array elements, strings, sets, maps | Yes |
for...in | Enumerable string keys | Object property enumeration | Yes |
forEach() | Value and index through a callback | Applying a callback to every array element | No direct loop break or continue |
forEach() is an array method rather than a language-level loop statement. A return inside its callback returns from that callback only; it does not return from the containing function or stop all remaining callbacks. Choose for...of when early termination is required.
const temperatures: number[] = [28, 31, 29];
temperatures.forEach((temperature, index) => {
console.log(`Reading ${index + 1}: ${temperature}°C`);
});
Using break and continue in a TypeScript for loop
The break statement exits the nearest loop immediately. The continue statement skips the remainder of the current iteration and proceeds to the next one.
const values: number[] = [4, -1, 7, 0, 9];
for (const value of values) {
if (value < 0) {
continue;
}
if (value === 0) {
break;
}
console.log(value);
}
Output
4
7
The negative value is skipped by continue. When the loop reaches zero, break stops processing, so the final value is never visited.
TypeScript for loop practices and common errors
- Declare loop counters with
letso their scope is limited to the loop. - Use
constfor afor...ofvalue when the loop variable itself is not reassigned. - Prefer
for...oftofor...inwhen iterating over array values. - Check the condition boundary carefully to avoid skipped elements and out-of-range indexes.
- Ensure the update expression moves the counter toward the stopping condition.
- Avoid changing an array’s length while an index-based loop is traversing it unless that mutation is part of a deliberate algorithm.
- Use array methods such as
map(),filter(), orreduce()when their returned transformation states the intended operation more clearly.
TypeScript for loop editorial QA checklist
- Verify that each index-based array loop uses a valid boundary such as
index < array.length. - Confirm that the counter update moves toward the loop’s termination condition.
- Check that
for...ofis used for iterable values andfor...inonly where property keys are intended. - Test empty arrays, one-element arrays, and the final iteration for off-by-one errors.
- Confirm that any
breakorcontinuestatement affects the intended enclosing loop.
TypeScript for loop FAQs
What is the syntax of a for loop in TypeScript?
The syntax is for (initialization; condition; update) { statements }. Initialization runs once, the condition is checked before each iteration, and the update runs after each completed iteration.
How do I get the index in a TypeScript for loop?
Use a classic loop with a numeric counter, such as for (let i = 0; i < items.length; i++). If early exit is unnecessary, an array’s forEach() callback also receives the index as its second argument.
What is the difference between for…in and for…of in TypeScript?
for...in enumerates string property keys, while for...of retrieves values from an iterable. For an array, for...in produces keys such as "0", whereas for...of produces the actual elements.
How do I loop through an array of objects in TypeScript?
Declare an interface or type for the elements and use for...of when only each object is needed. Use a classic index-based loop when the object’s array position is also required.
Can I use break or continue with TypeScript forEach?
No. forEach() does not support normal loop break or continue behavior. Use a for or for...of loop when iteration must stop early or skip directly to the next iteration.
Conclusion
In this TypeScript Tutorial, we covered classic counter and range loops, indexed array iteration, for...of values, for...in property keys, forEach(), and loop control with break and continue.
TutorialKart.com