A TypeScript for loop is the same loop you know from JavaScript, with types inferred on top: use for (let i = 0; i < items.length; i++) when you need the index, for (const item of items) for the values, and avoid for...in on arrays. This page compares the four common variants (classic for, for...of, for...in and forEach) and shows what type each one gives you.
For the base syntax, break and continue, see JavaScript for loop: syntax, examples and for...of vs for...in. Everything there applies to TypeScript. This article covers what TypeScript adds.
The four loops side by side
All four examples loop over the same array. The comments show the type TypeScript infers for the loop variable. The array is annotated once and nothing else needs a type.
const names: string[] = ["Alice", "Bob", "Eve"];
// 1. Classic for: i is number, names[i] is string
for (let i = 0; i < names.length; i++) {
console.log(i, names[i].toUpperCase());
}
// 2. for...of: name is string
for (const name of names) {
console.log(name.toUpperCase());
}
// 3. for...in: key is string (the index as text, "0", "1", "2")
for (const key in names) {
console.log(key);
}
// 4. forEach: name is string, index is number
names.forEach((name, index) => {
console.log(index, name.toUpperCase());
});
The handbook's Everyday Types page says TypeScript infers variable types from their initializers and gives anonymous function parameters their types from context, so in names.forEach((s) => ...) the parameter s is a string. The same inference gives name its type in the for...of loop. You can confirm each comment above by hovering over the variable in your editor.
| Loop | Gives you | Can break | Waits for await | Use it for |
|---|---|---|---|---|
Classic for | Index (number) | Yes | Yes | Index math, reverse or stepped loops |
for...of | Each value | Yes | Yes | Most array and iterable loops |
for...in | Each key (string) | Yes | Yes | Keys of a plain object, with care |
forEach | Value and index | No | No | Short synchronous side effects |
Classic for: when you need the index
The three-part loop is the right choice when the index itself matters: counting backwards, stepping by two, comparing neighbours, or writing into a second array at the same position.
const scores: number[] = [4, 8, 15, 16, 23, 42];
for (let i = scores.length - 1; i >= 0; i -= 2) {
console.log(i, scores[i]);
}
Example output: 5 42, then 3 16, then 1 8. Declare the counter with let, not var, so each iteration gets its own binding. Use const only when the variable is never reassigned, which rules it out for the counter here.
for...of: the default for arrays
When you only need the values, for...of has nothing to get wrong: no counter to miscount, no off-by-one at the end, and the variable is already the element type. It also works on strings, Map, Set and anything else that implements Symbol.iterator. If you want the index too, iterate names.entries() and destructure each pair:
for (const [index, name] of names.entries()) {
console.log(index, name);
}
Both break and continue work, and an await inside the body pauses the loop, which makes this the loop to reach for when each step must finish before the next one starts.
async function sendAll(urls: string[]): Promise<void> {
for (const url of urls) {
const response = await fetch(url);
console.log(url, response.status);
}
}
for...in: keys, not values
The variable in a for...in loop is always a string, because it walks property keys. MDN shows that with an array, the loop prints "string 0" and "string 1", so using the key as a number needs a conversion, and arithmetic like key + 1 produces a string join, not a sum.
It is also broader than most people expect. MDN says it visits all enumerable string-keyed properties of an object, including inherited enumerable ones, and it also returns non-index properties that someone has put on an array. In MDN's example, an array with an extra property extra yields "0", "1" and "extra" from for...in, but only the two elements from for...of. MDN recommends a numeric for loop, forEach() or for...of for arrays.
For a plain object, a safer pattern is to loop over Object.keys(), which returns only the object's own enumerable string keys:
const prices: Record<string, number> = { apple: 1.2, pear: 0.9 };
for (const key of Object.keys(prices)) {
console.log(key, prices[key]);
}
Here key is a string and the object is a Record<string, number>, so prices[key] is a number. If you do use for...in on an object with a prototype chain, MDN suggests guarding with Object.hasOwn(obj, key).
forEach: convenient, but no break and no await
forEach is a method, not a statement, and that has three consequences straight from MDN:
- No early exit. MDN says there is no way to stop a
forEach()loop other than throwing an exception, and that if you need that, the method is the wrong tool. Usesome(),every(),find()orfindIndex(), or switch to afororfor...ofloop. - It ignores promises. MDN says
forEach()expects a synchronous function and does not wait for promises. Its example uses an async callback to add up[5, 4, 5]; the expected result is 14, but the printed result is 0. - It skips empty slots. In a sparse array such as
[2, 5, , 9], the callback runs for indexes 0, 1 and 3 only.
A return inside the callback only ends that one call, like continue in a normal loop. The method itself always returns undefined, so you cannot chain it.
The ES5 target catch with for...of
If your tsconfig.json compiles to a modern target, for...of is emitted as is and you can ignore this section. If you target ES5, the TSConfig reference describes a difference. Without downlevelIteration, TypeScript turns for...of into an index-based loop. On a string, the emitted code looks like this (from the TypeScript docs):
var str = "Hello!";
for (var _i = 0, str_1 = str; _i < str_1.length; _i++) {
var s = str_1[_i];
console.log(s);
}
The docs note this is not fully compliant with how JavaScript iterates. Their example is emoji: some have a .length of 2 but should be visited as one unit by for...of. Setting "downlevelIteration": true makes TypeScript emit a helper that uses Symbol.iterator when the runtime has one. The docs add that the flag does not help if Symbol.iterator is missing in the runtime. The flag was released in TypeScript 2.3, and the same option governs array spread and argument spread under ES5.
{
"compilerOptions": {
"target": "ES5",
"downlevelIteration": true
}
}
Which loop should you pick?
- Need each value, and maybe
awaitorbreak:for...of. - Need the index, a reverse loop or a custom step: classic
for. - Need to visit the keys of a plain object:
for (const key of Object.keys(obj)). - Short, synchronous, no early exit:
forEachis fine, and so aremapandfilterwhen you want a new array. - Arrays with
for...in: avoid.
Frequently asked questions
- Do I need to type the loop variable in a TypeScript for loop?
- Usually not. TypeScript infers the variable from what you iterate, so annotating the array (for example names: string[]) is enough. The Everyday Types page of the handbook recommends using fewer annotations than you might expect, because types are inferred from initializers and context.
- Why is the variable in a TypeScript for...in loop a string?
- for...in visits property keys, and keys are strings. MDN shows that even for an array, typeof the loop variable is "string", with values like "0" and "1". If you want the elements or numeric indexes of an array, use for...of or a classic for loop.
- Can I use break inside forEach in TypeScript?
- No. TypeScript compiles to JavaScript, and MDN states that there is no way to stop a forEach() loop other than throwing an exception. Use a classic for loop or for...of when you need to stop early, or use some(), every(), find() or findIndex().
- Does await work inside a forEach callback?
- The callback can be async, but forEach() does not wait for the promises it returns. MDN's example sums three ratings with an async callback and prints 0 instead of 14. To run awaited steps one after another, put await inside a for...of or classic for loop in an async function.